7

我正在使用:

cat <<<"${MSG}" > outfile

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

但是现在我的程序中的逻辑发生了变化,所以我必须首先 outfile通过从我的程序中附加行awk(从我的 bash 脚本外部调用)来填充,然后作为最后一步${MSG}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}
4

3 回答 3

5

使用命令组:

{
    echo "$MSG"
    awk '...'
} > outfile

如果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

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

cat <(echo $MSG) outfile <(awk '...') > outfile.new && mv outfile.new outfile
于 2014-07-08T14:10:10.003 回答
5

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

awk '1' <(echo "$MSG") file

甚至这echo应该工作:

echo "${MSG}$(<file)" > file
于 2014-07-08T14:12:03.927 回答
4

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

{ cat - old-file >new-file && mv new-file old-file; } <<EOF
header
EOF
于 2014-07-08T15:34:53.480 回答