Bash sed用文件内容替换文本

时间:2015-06-25 17:10:40

标签: linux bash sed

我想用file.txt内容替换字符串。

mtn="John"
fs=`cat file.txt`
lgtxt=`cat large_text.txt`

stxt1=`echo $lgtxt | sed "s/zzzz/$mtn/g"`
stxt2=`echo $stxt1 | sed "s/pppp/$fs/g"`

它取代了' zzzz'价值为' mnt'但是没有' pppp' 文件file.txt包含名称列表,例如: 汤姆琼斯 泰德贝克 琳达埃文斯 在单独的行中。 我想将它们放在文件large_text.txt中的单独行中,就像它们在oryginal文件中一样,并用逗号分隔。

1 个答案:

答案 0 :(得分:8)

您不希望使用变量进行替换(例如,因为它可能包含换行符)。我假设它是GNU sed给它的。在这种情况下,请查看GNU sed的r命令是否可以帮助您:

`r FILENAME'
     As a GNU extension, this command accepts two addresses.

     Queue the contents of FILENAME to be read and inserted into the
     output stream at the end of the current cycle, or when the next
     input line is read.  Note that if FILENAME cannot be read, it is
     treated as if it were an empty file, without any error indication.

     As a GNU `sed' extension, the special value `/dev/stdin' is
     supported for the file name, which reads the contents of the
     standard input.

如果pppp在自己的一行上,你可以选择

/pppp/{
r file.txt
d
}

或者,使用s修饰符的e命令:

`e'
     This command allows one to pipe input from a shell command into
     pattern space.  If a substitution was made, the command that is
     found in pattern space is executed and pattern space is replaced
     with its output.  A trailing newline is suppressed; results are
     undefined if the command to be executed contains a NUL character.
     This is a GNU `sed' extension.

这看起来像

s/pppp/cat file.txt/e

并且如果pppp处于中线状态,您就需要这样做。此外,如果您需要在file.txt上进行进一步处理,则可以将cat替换为您需要的任何内容(尽管您需要注意引用/\)。

最后一个选择是考虑Perl,它将接受与shell命令非常相似的东西。