在 bash 中将 **heredoc** 添加到文件中

bra*_*ito 5 bash prepend herestring

我正在使用:

cat <<<"${MSG}" > outfile
Run Code Online (Sandbox Code Playgroud)

首先向 写入消息outfile,然后继续进行进一步处理,这将附加到outfile我的 awk 脚本中。

但现在已逻辑在我的计划改变了,所以我得先填入 outfile从我的附加线awk计划(从我的bash脚本外部调用),然后在最后一步前插是$ {}味精heredoc我的头outfile。 .

我怎么能从我的 bash 脚本而不是 awk 脚本中做到这一点?

编辑

这是味精heredoc

read -r -d '' MSG << EOF
-----------------------------------------------
--   results of processing - $CLIST
--   used THRESHOLD ($THRESHOLD)
-----------------------------------------------
l
EOF
# trick to pertain newline at the end of a message
# see here: http://unix.stackexchange.com/a/20042
MSG=${MSG%l}
Run Code Online (Sandbox Code Playgroud)

che*_*ner 5

使用命令组:

{
    echo "$MSG"
    awk '...'
} > outfile
Run Code Online (Sandbox Code Playgroud)

如果outfile已经存在,您别无选择,只能使用临时文件并将其复制到原始文件上。这是由于所有(?)文件系统如何实现文件;您不能添加到流之前。

{
     # You may need to rearrange, depending on how the original
     # outfile is used.
     cat outfile
     echo "$MSG"
     awk '...'
} > outfile.new && mv outfile.new outfile
Run Code Online (Sandbox Code Playgroud)

您可以使用的另一个非 POSIX 功能cat是进程替换,它使任意命令的输出看起来像一个文件cat

cat <(echo $MSG) outfile <(awk '...') > outfile.new && mv outfile.new outfile
Run Code Online (Sandbox Code Playgroud)

  • `&lt;&lt;&lt;` 提供标准输入,而 `cat` 在收到一个或多个文件名参数时会忽略标准输入。 (2认同)

anu*_*ava 5

您可以使用awk在文件开头插入多行字符串:

awk '1' <(echo "$MSG") file
Run Code Online (Sandbox Code Playgroud)

或者甚至这echo应该有效:

echo "${MSG}$(<file)" > file
Run Code Online (Sandbox Code Playgroud)


Cha*_*ffy 5

用作命令行上要插入新内容的点的-占位符:cat

{ cat - old-file >new-file && mv new-file old-file; } <<EOF
header
EOF
Run Code Online (Sandbox Code Playgroud)

  • +1 用于前缀形式,但使用 `cat &lt;&lt;EOF &gt;&gt;old-file` 作为后缀形式更简单。 (2认同)