将变量写入文件的特定行末尾

将变量写入文件的特定行末尾

我想添加一个变量结尾具体的文件中的行file.txt。到目前为止我的代码:

#!/bin/bash    
read -p "What is the path of the repo? > " input
echo :$input  >> file.txt

我想将它添加到结束2号线。 例如,

file.txt
--------
before -
1.stuff 
2./home/retep/awesome

after -
1.stuff
2./home/retep/awesome:/home/retep/cool

答案1

这是 awk 的另一个单行命令:

#!/bin/bash    
read -p "What is the path of the repo? > " input

awk -v addition="$input" -v targetline=2 '
NR==targetline { print $0 ":" addition; next}
{print }' file.txt > file.tmp
mv file.tmp file.txt

相关内容