Regular/替换指定行内容
来自康健生活
< Regular
替换指定行内容
sed
某文件夹下有三个文件
# 1.txt $host = "1.1.1.1"; $host = "1.1.1.1"; $host = "1.1.1.1"; $host = "1.1.1.1"; # 2.txt $host = '11.11.11.11'; $host = '11.11.11.11'; $host = '11.11.11.11'; $host = '11.11.11.11'; # 3.txt $host = <111.111.111.111>; $host = <111.111.111.111>; $host = <111.111.111.111>; $host = <111.111.111.111>;
整理出需要替换内容的列表保存在replace.me的文件里,格式为文件名:需替换的行号 该行的内容
1.txt:1 $host = "1.1.1.1"; 2.txt:2 $host = '11.11.11.11'; 3.txt:3 $host = <111.111.111.111>;
使用sed+正则表达式将replace.me的文件里每个文件名里出现的ip地址用正则表达式进行匹配,并将匹配到的地址替换为2.2.2.2,替换后的结果为
# 1.txt $host = "2.2.2.2"; $host = "1.1.1.1"; $host = "1.1.1.1"; $host = "1.1.1.1"; # 2.txt $host = '11.11.11.11'; $host = '2.2.2.2'; $host = '11.11.11.11'; $host = '11.11.11.11'; # 3.txt $host = <111.111.111.111>; $host = <111.111.111.111>; $host = <2.2.2.2>; $host = <111.111.111.111>;
$ sed -r 's/^(.*):([0-9]+).*=[^0-9]*([0-9\.]+)[^0-9]+$/sed "1F;\2 s#\3#2.2.2.2#" \1/e;' re.me
1.txt
$host = "2.2.2.2";
$host = "1.1.1.1";
$host = "1.1.1.1";
$host = "1.1.1.1";
2.txt
$host = '11.11.11.11';
$host = '2.2.2.2';
$host = '11.11.11.11';
$host = '11.11.11.11';
3.txt
$host = <111.111.111.111>;
$host = <111.111.111.111>;
$host = <2.2.2.2>;
$host = <111.111.111.111>;
如果直接修改原文件,修改为以下内容
sed -r 's/^(.*):([0-9]+).*=[^0-9]*([0-9\.]+)[^0-9]+$/sed -i "\2 s#\3#2.2.2.2#" \1/e;' re.me
awk 'BEGIN{FS="[: <>;\"'"'"'=]+";while(getline <"replace.me"){a[$1]=$2;b[$1]=$4}} a[FILENAME]==FNR{gsub(b[FILENAME],"2.2.2.2")}{print >FILENAME"new"}' files
awk -F '[: ]+' '{n=0;while(getline v<$1){if(++n==$2)sub(/\<[0-9.]+\>/,"2.2.2.2",v);print v>$1".new"}}' replace.me
No categories