shell替换指定字符串和替换最后一个出现字符串

#!/bin/bash
awk '$0=="aaa"{a[$1]++;if(a[$1]==1){print "helloworld"}else{print}}$0!="aaa"{print}' 222.txt >> tmp.txt
cp tmp.txt 222.txt
rm -rf  tmp.txt
awk '$0=="aaa"{a[$1]++;if(a[$1]==2){print "apple"}else{print}}$0!="aaa"{print}' 222.txt >> tmp.txt
cp tmp.txt 222.txt
rm -rf tmp.txt
count=$(grep -o 'ccc' 222.txt |wc -l)
echo "aa$count"
awk '$0=="ccc"{a[$1]++;if(a[$1]=='${count}'){print "xyzxyz"}else{print}}$0!="ccc"{print}' 222.txt >> tmp.txt
cp tmp.txt 222.txt
rm -rf tmp.txt

把文件222.txt里第一个出现的aaa替换为abcdefg

sed -i '0,/aaa/s//abcdefg/' 222.txt

改进版本

#!/bin/bash
sed -i '0,/aaa/s//helloworld/' 222.txt
awk '$0=="aaa"{a[$1]++;if(a[$1]==2){print "apple"}else{print}}$0!="aaa"{print}' 222.txt > tmp.txt && mv tmp.txt 222.txt
count=$(grep -o 'ccc' 222.txt |wc -l)
awk '$0=="ccc"{a[$1]++;if(a[$1]=='${count}'){print "xyzxyz"}else{print}}$0!="ccc"{print}' 222.txt > tmp.txt && mv tmp.txt 222.txt

你可能感兴趣的:(shell,vim,bash)