Bash 将 heredoc 内容直接插入到输出文件中的特定位置 w/o 临时文件?
Bash insert heredoc contents directly to specific place in output file w/o temporary file?
是否可以在没有临时文件的情况下将 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
。
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
这需要您的文件系统的一些支持,但是
sed -i '10 r /dev/stdin' outputfile <<EOF
additional
lines
EOF
会起作用。但是,如果您直接在脚本中而不是在真实文件中指定文本,则 a\
命令可能更合适:
sed -i '10a\
additional\
lines\
' outputfile
是否可以在没有临时文件的情况下将 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
。
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
这需要您的文件系统的一些支持,但是
sed -i '10 r /dev/stdin' outputfile <<EOF
additional
lines
EOF
会起作用。但是,如果您直接在脚本中而不是在真实文件中指定文本,则 a\
命令可能更合适:
sed -i '10a\
additional\
lines\
' outputfile