是否可以将heredoc内容直接插入输出文件中的特定行而不使用临时文件?
cat <<-EOT > tmp.txt
some string
another string
and another one
EOT
sed -i '10 r tmp.txt' outputfile && rm tmp.txt
我一直在使用这样的东西,但我更愿意避免需要tmp.txt
。
答案 0 :(得分:2)
ed
可能是一个不错的选择
# 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
1
2
3
4
5
6
7
8
9
some string
another string
and another one
10
11
12
13
14
15
您可以合并两个heredoc来保存一个步骤:
ed file <<-EOF
10i
some string
another string
and another one
.
wq
EOF
答案 1 :(得分:1)
这需要您的文件系统提供一些支持,但
sed -i '10 r /dev/stdin' outputfile <<EOF
additional
lines
EOF
会奏效。但是,如果直接在脚本中指定文本而不是实际文件,则a\
命令可能更合适:
sed -i '10a\
additional\
lines\
' outputfile