【发布时间】:2021-12-19 22:54:07
【问题描述】:
我想使用单个命令行(我尝试通过管道和进程替换来执行此操作,但未成功,如下所述)将home_cool 和home_cool01 的每第n 次出现替换为a 的第n 行提供的文件,最好不要使用管道,而是添加 home_cool01 作为在命令中获取的另一个模式。
知道0.txt 包含2 次em> home_cool 和2 次em> home_cool01。
我有这个命令(按顺序使用),将home_cool 和home_cool01 的第n 次出现替换为所提供文件1.txt 的第n 行,如下所示:
awk 'NR==FNR {a[NR]=$0; next} /home_cool/{gsub("home_cool", a[++i])} 1' 1.txt 0.txt > 2.txt
和
awk 'NR==FNR {a[NR]=$0; next} /home_cool01/{gsub("home_cool01", a[++i])} 1' 1.txt 2.txt > 3.txt
但即使使用pipe,我也不想要两个单独的命令。
这是我的文件:
文件0.txt 波纹管:
"#sun\t",
"\t",
"bread = door('dog', 'paint')\t",
"door = world.sea\t",
"world.sea = bread\t",
"\t",
"machine(\"home_cool\")\t",
"\t",
"car_snif = house.group_tree(home_cool)\t",
"\t",
"machine(shoes_shirt.shop)\t",
"machine(car_snif.car_snif)\t",
"door = world.sea\t",
"world.sea = bread\t",
"\t",
"machine(\"home_cool01\")\t",
"\t",
"car_snif = house.group_tree(home_cool01)\t",
"\t",
"machine(shoes_shirt.shop)\t",
"machine(car_snif.car_snif)\t",
flle 1.txt 如下:
(food, apple, sky, cat,blue,)(bag, tortoise,)
(food, apple, sky, cat,blue,)(bag,)
(food, apple, sky, cat,blue,)(bag, moon, tortoise,)
我想要的结果是下面的 2.txt:
"#sun\t",
"\t",
"bread = door('dog', 'paint')\t",
"door = world.sea\t",
"world.sea = bread\t",
"\t",
"machine(\"(food, apple, sky, cat,blue,)(bag, tortoise,)\")\t",
"\t",
"car_snif = house.group_tree((food, apple, sky, cat,blue,)(bag,))\t",
"\t",
"machine(shoes_shirt.shop)\t",
"machine(car_snif.car_snif)\t",
"door = world.sea\t",
"world.sea = bread\t",
"\t",
"machine(\"(food, apple, sky, cat,blue,)(bag, tortoise,)\")\t",
"\t",
"car_snif = house.group_tree((food, apple, sky, cat,blue,)(bag,))\t",
"\t",
"machine(shoes_shirt.shop)\t",
"machine(car_snif.car_snif)\t",
注意:我可以将此问题视为Replace each nth occurrence of 'foo' by numerically respective nth line of a supplied file 的子问题 我想过通过聊天或 cmets 来帮助这个子问题的作者,但我相信这是一个新问题,所以我在操作系统上开了一个新帖子。
【问题讨论】:
-
如果您可以将其简化为 minimal reproducible example(1 个小脚本、1 个小样本输入文件、相关的预期输出、无滚动条以及您要执行的操作的简明陈述以及您寻求帮助的问题)然后更多的人将有时间花时间阅读您的问题以尝试帮助您。
-
@EdMorton 我会将模式的出现次数减少到 2 次而不是 4 次。
-
如果最终结果是您的问题仍然包含 5 个 awk 脚本和带有滚动条的示例输入,那么这将无济于事。
标签: awk command-line gsub find-occurrences