我有以下两个文本文件
A.TXT:
Hello, my name is <name>
and I like flowers.
b.txt:
Susan
Katie
Caitlynn
我想操纵它以在c.txt中输出以下内容:
Hello, my name is Susan
and I like flowers.
Hello, my name is Katie
and I like flowers.
Hello, my name is Caitlynn
and I like flowers.
依此类推。
我可以在一个实例中替换它们,但不知道如何连续读取b.txt以继续替换
答案 0 :(得分:0)
您可以使用awk
:
awk 'FNR==NR{a[$1]++; next}
{for (i in a) { s=$0; sub(/<name>/, i, s); print s}}' b.txt a.txt
Hello, my name is Caitlynn
Hello, my name is Susan
Hello, my name is Katie
更新:根据已修改的问题:
awk 'FNR==NR{a[$1]++; next} /<name>/{curLine=$0; getline nextLine;
for (i in a) {s=curLine; sub(/<name>/, i, s); print s; print nextLine}}' b.txt a.txt
Hello, my name is Caitlynn
and I like flowers.
Hello, my name is Susan
and I like flowers.
Hello, my name is Katie
and I like flowers.
答案 1 :(得分:0)
以下是sed
解决方案:
$ sed -r '1{h;d}; G; s/(.*)\n(.*)<name>(.*)/\2\1\3/' a.txt b.txt
Hello, my name is Susan
Hello, my name is Katie
Hello, my name is Caitlynn
1{h;d}
sed
看到的第一行来自a.txt
。这会将该行保存在保留空间中,然后跳过以从下一行重新开始。
G
第二行和所有后续行来自b.txt
。对于每个这样的行,此命令将保留空间附加到该行。执行此操作后,模式空间的名称(来自b.txt
)后跟换行符,后跟a.txt
中的行。
s/(.*)\n(.*)<name>(.*)/\2\1\3/
这会重新排列模式空间,将名称放在应有的位置。
$ sed -r '1{h;d}; 2{H;d}; G; s/(.*)\n(.*)<name>(.*)/\2\1\3/' a2.txt b.txt
Hello, my name is Susan
and I like flowers.
Hello, my name is Katie
and I like flowers.
Hello, my name is Caitlynn
and I like flowers.
答案 2 :(得分:0)
您也可以尝试使用sed + bash循环:
for x in $(cat b.txt); do sed -e "s/<name>/$x/" a.txt; done
如果句子之间需要额外的行
for x in $(cat b.txt); do sed -e "s/<name>/$x/" a.txt; echo ""; done
答案 3 :(得分:0)
$ awk 'NR==FNR{tmplt=tmplt $0 ORS; next} {block=tmplt; sub(/<name>/,$0,block); print block}' a.txt b.txt
Hello, my name is Susan
and I like flowers.
Hello, my name is Katie
and I like flowers.
Hello, my name is Caitlynn
and I like flowers.
答案 4 :(得分:0)
使用sed战术性地使用e command
,如下所示
sed 's#.*#sed "s/\\(.*\\)<name>\\(.*\\)/\\n\\1&\\2/" a.txt #e' b.txt > c.txt
其中c.txt
是具有预期结果的新文件
结果
Hello, my name is Susan
and I like flowers.
Hello, my name is Katie
and I like flowers.
Hello, my name is Caitlynn
and I like flowers.