【问题标题】:Bash sed replace text with file contentBash sed 用文件内容替换文本
【发布时间】:2015-06-26 04:44:21
【问题描述】:

我想用 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"`

它用 'mnt' 的值替换 'zzzz' 但不是 'pppp'。 文件 file.txt 包含名称列表,例如: 汤姆琼斯 特德贝克 琳达·埃文斯 在单独的行中。 我想将它们放在文件 large_text.txt 中的单独行中,就像它们在原始文件中一样,并用逗号分隔。

【问题讨论】:

  • m4(1) 是你的朋友。
  • pppp 是否在单独的行上只出现一次?在这种情况下,我们可以寻找另一种通过 pppp 行拆分 lgtxt 的解决方案。还是 pppp 出现在某些行if [ "${line}" = "pppp" ]; then ...
  • 不会在句子中出现,而且不止一次。
  • 显示一些示例输入和预期输出,这样我们就不必猜测了。
  • cat file.txt code Tom Jones Ted Baker Linda Evans cat large_file.txt 这是我们学生 pppp 的名单。 pppp是我们班的学生。预期输出:这是我们的学生 Tom jones Ted Baker Linda Evans 的名单。汤姆琼斯泰德贝克琳达埃文斯是我们班的学生。

标签: linux bash sed


【解决方案1】:

您不想使用变量进行替换(例如,因为它很可能包含换行符)。我假设它是 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
}

或者,或者,带有e修饰符的s命令:

`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 命令非常相似的内容。

【讨论】:

  • code sed -i '/pppp/r file.txt' large_text.txt code 几乎解决了这个问题 ;-) 。为了获得完美的结果,我需要在替换后删除“pppp”。相同情况但替换的文字需要用逗号分隔怎么办?
  • @Marcin:我已经编辑以解决您的后续评论。
猜你喜欢
  • 2018-10-09
  • 2012-09-10
  • 2014-02-09
  • 1970-01-01
  • 2022-10-21
  • 1970-01-01
  • 2021-03-21
  • 2013-04-30
  • 2022-01-05
相关资源
最近更新 更多