如何用单条命令行按另一文件行范围替换不同文件的指定字符串
多文件批量替换单命令实现方案
基础文件说明
0.txt和0-1.txt内容完全一致,内容如下:
"#sun\t", "car_snif = house.group_tree(home_cool)\t", "machine(shoes_shirt.shop)\t", "car_snif = house.group_tree(home_cool)\t", "machine(shoes_shirt.shop)\t", "car_snif = house.group_tree(home_cool)\t", "machine(shoes_shirt.shop)\t", "car_snif = house.group_tree(home_cool)\t", "machine(shoes_shirt.shop)\t", "#sun\t", "car_snif = house.group_tree(home_cool)\t", "machine(shoes_shirt.shop)\t", "car_snif = house.group_tree(home_cool)\t", "machine(shoes_shirt.shop)\t", "car_snif = house.group_tree(home_cool)\t", "machine(shoes_shirt.shop)\t", "car_snif = house.group_tree(home_cool)\t",
- 源文件
1.txt内容如下:
(food, apple,)(bag, tortoise,) (sky, cat,)(sun, sea,) (car, shape)(milk, market,) (man, shirt)(hair, life) (dog, big)(bal, pink)
需求说明
- 处理
0.txt:将其中home_cool每2次连续出现替换为1.txt前2行内容,每个替换值连续使用2次,循环复用,最终结果输出到2.txt。 - 处理
0-1.txt:将其中home_cool每2次连续出现替换为1.txt第3行到第5行内容,每个替换值连续使用2次,循环复用,最终结果输出到3.txt。
单命令实现方案
使用单条awk命令即可完成全部操作,无需拆分多个独立处理片段:
awk 'NR==FNR{arr[NR]=$0;next}FILENAME=="0.txt"{if(/home_cool/){cnt1++;repl_idx=int((cnt1-1)/2)%2+1;gsub("home_cool",arr[repl_idx])}print > "2.txt";next}FILENAME=="0-1.txt"{if(/home_cool/){cnt2++;repl_idx=int((cnt2-1)/2)%3+3;gsub("home_cool",arr[repl_idx])}print > "3.txt"}' 1.txt 0.txt 0-1.txt
如果需要可读性更高的版本,可展开为多行格式:
awk ' # 预加载1.txt的所有内容到数组 NR == FNR { arr[NR] = $0 next } # 处理0.txt,输出到2.txt FILENAME == "0.txt" { if (/home_cool/) { cnt1++ # 按规则取1.txt前2行循环替换 repl_idx = int((cnt1 - 1) / 2) % 2 + 1 gsub("home_cool", arr[repl_idx]) } print > "2.txt" next } # 处理0-1.txt,输出到3.txt FILENAME == "0-1.txt" { if (/home_cool/) { cnt2++ # 按规则取1.txt第3-5行循环替换 repl_idx = int((cnt2 - 1) / 2) % 3 + 3 gsub("home_cool", arr[repl_idx]) } print > "3.txt" } ' 1.txt 0.txt 0-1.txt
内容的提问来源于stack exchange,提问作者7beggars_nnnnm
相关产品推荐
相关产品推荐

