Bash是否将herdoc内容直接插入到输出文件中的特定位置,而不插入临时文件?
是否可以在不使用临时文件的情况下将heredoc内容直接插入输出文件中的特定行Bash是否将herdoc内容直接插入到输出文件中的特定位置,而不插入临时文件?,bash,heredoc,Bash,Heredoc,是否可以在不使用临时文件的情况下将heredoc内容直接插入输出文件中的特定行 cat <<-EOT > tmp.txt some string another string and another one EOT sed -i '10 r tmp.txt' outputfile && rm tmp.txt cated可能是一个不错的选择 # create a test file seq 15 >
cat <<-EOT > tmp.txt
some string
another string
and another one
EOT
sed -i '10 r tmp.txt' outputfile && rm tmp.txt
cated
可能是一个不错的选择
# create a test file
seq 15 > file
# save the heredoc contents in a variable
new=$(cat <<-EOT
some string
another string
and another one
EOT
)
# note the close parenthesis must **not** be on the same line as the heredoc word
# add the contents into the file
ed file <<EOF
10i
$new
.
wq
EOF
cat file
您可以合并两个heredocs以保存一个步骤:
ed file <<-EOF
10i
some string
another string
and another one
.
wq
EOF
ed file这需要您的文件系统提供一些支持,但是
sed -i '10 r /dev/stdin' outputfile <<EOF
additional
lines
EOF
我不明白这个脚本在做什么。尤其是sed
行。不过,我可不是酒鬼。什么是'10r tmp.txt'
?r
命令读取指定地址的文件。在tmp.txt中写入herdoc内容。sed在现有文本之间的输出文件第10行插入tmp.txt。有点令人惊讶的是,-
不是r
的有效参数,尽管sed
从标准输入读取要编辑的文件可能太常见了,不值得支持这种重叠。记住@glennjackman的ed
答案,不过ed
确实是编辑文件的正确工具,sed
更适合于流(这就是s
所代表的)ed file.txt
,但是。|sed“…”|…
。在OpenBSD上,必须在行后添加\并在另一行上添加“outputfile”。更好!应该提到要插入的代码在脚本中。哦,对了。我在macOS上对此进行了测试,但没有仔细查看输出结果以发现缺少的换行符。
sed -i '10 r /dev/stdin' outputfile <<EOF
additional
lines
EOF
sed -i '10a\
additional\
lines\
' outputfile