首页 > 解决方案 > 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

我一直在使用这样的东西,但我宁愿避免需要tmp.txt

标签: bashheredoc

解决方案


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

您可以合并两个 heredocs 以节省一个步骤:

ed file <<-EOF
    10i
    some string
            another string

            and another one
    .
    wq
EOF

推荐阅读