<code>Replace a string with each line from another file</code>

时间:2013-08-27 03:19:46

标签: bash sed

我有2个文件: FILE1.TXT

Monday XXXX
Tuesday XXXX
XXXX Wednesday
Thursday XXXX

XXXX位于file1.txt的每一行,我想用file2.txt中的每一行替换它们:

home
school
cinema

所以输出文件是:

Monday home
Tuesday home
home Wednesday
Thursday home
Monday school
Tuesday school
school Wednesday
Thursday school
Monday cinema
Tuesday cinema
cinema Wednesday
Thursday cinema

我得到了file2.txt有很多行,所以我不能手工完成。所以,我需要一个解决方案。 谢谢你的时间。

4 个答案:

答案 0 :(得分:1)

简单如下:

while read i 
do
    sed s/XXXX/$i/ file1.txt
done < file2.txt > output

您在寻找什么?

答案 1 :(得分:0)

这可能适合你(GNU sed):

sed 's|.*|sed s/XXXX/&/g file1|e' file2

这使用GNU特定的e标志在sed命令中运行sed命令。

或者您可以将生成的sed命令传递给shell:

sed 's|.*|sed s/XXXX/&/g file1|' file2 | sh

答案 2 :(得分:0)

另一个单独的awk命令:

awk 'BEGIN { while ((getline line < ARGV[1]) > 0) a[i++] = line; ARGV[1] = ""; } { for (i = 1; i in a; ++i) { t = a[i]; gsub(/XXXX/, $0, t); print t }; }' file1 file2

答案 3 :(得分:0)

$ awk 'NR==FNR{r=r $0 ORS;next} {t=r; gsub(/XXXX/,$0,t); printf "%s",t}' file1 file2
Monday home
Tuesday home
home Wednesday
Thursday home
Monday school
Tuesday school
school Wednesday
Thursday school
Monday cinema
Tuesday cinema
cinema Wednesday
Thursday cinema