bash - 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
。
解决方案
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
推荐阅读
- python - Sort specific columns in pandas
- php - How to set selected value in html dropdown if name is array using codeigniter?
- embedded-linux - What's the 'correct' way to stage optional server certificates for a bitbake recipe?
- javascript - 如何在页面上添加数百个形状而不减慢页面加载速度
- huawei-mobile-services - Huawei IAP error in Flutter - Integrate the version update API (checkUpdate)
- collections - How do I merge two dictionaries in Smalltalk with a oneliner?
- android - 如何更改片段的语言运行时
- python - remove spaces at the beginning from array
- postgresql - 在 Postgres 中获得较高的查询执行时间
- css - CSS - 如何导入 TTF 字体的所有变体(在 TFF 文件中列出)