首页 > 解决方案 > 使用具有单行的另一个文件的内容为文件的内容添加前缀

问题描述

我正在尝试将 a 的内容file1.txt插入file2.txtusing sed. 的内容file1.txt只是一行,是一条路径。我希望将它作为前缀添加到每一行file2.txt以及添加另一个/字符。

$ cat file1.txt
/psot/rot8888/orce/db/tier/data/tine

$ cat file2.txt
o1_mf_users_abchwfg_.dbf
o1_mf_toptbs2_abchrq0_.dbf
o1_mf_toptbs1_abchrl2_.dbf
o1_mf_toptbs1_abchtlf_.dbf

所需的输出应如下所示:

/psot/rot8888/orce/db/tier/data/tine/o1_mf_users_abchwfg_.dbf
/psot/rot8888/orce/db/tier/data/tine/o1_mf_toptbs2_abchrq0_.dbf
/psot/rot8888/orce/db/tier/data/tine/o1_mf_toptbs1_abchrl2_.dbf
/psot/rot8888/orce/db/tier/data/tine/o1_mf_toptbs1_abchtlf_.dbf

试过的命令:

$ sed '/o1/ r file1.txt' file2.txt >> test.txt    
$ cat test.txt
o1_mf_users_abchwfg_.dbf
/psot/rot8888/orce/db/tier/data/tine
o1_mf_toptbs2_abchrq0_.dbf
/psot/rot8888/orce/db/tier/data/tine
o1_mf_toptbs1_abchrl2_.dbf
/psot/rot8888/orce/db/tier/data/tine
o1_mf_toptbs1_abchtlf_.dbf
/psot/rot8888/orce/db/tier/data/tine

标签: sed

解决方案


您可以使用pr它而不必担心sed元字符、分隔符等。

$ cat ip.txt
abcd.xyz
123.txt
foo_baz.txt
$ cat f1
/a/b/c/d/

$ pr -mts"$(< f1)" /dev/null ip.txt
/a/b/c/d/abcd.xyz
/a/b/c/d/123.txt
/a/b/c/d/foo_baz.txt

where-m允许并行粘贴文件,-s是要合并的文件之间的分隔符。在这里,/dev/null用作其中一个文件的虚拟对象,因为只有分隔符必须加上前缀。


如果您需要在包含前缀的文件内容之后添加更多字符:

$ cat ip.txt
abcd.xyz
123.txt
foo_baz.txt
$ cat f1
/a/b/c/d
$ pr -mts"$(< f1)"'/' /dev/null ip.txt
/a/b/c/d/abcd.xyz
/a/b/c/d/123.txt
/a/b/c/d/foo_baz.txt

推荐阅读