将文件的内容插入另一个文件(在发送的文件的特定行中)-BASH/LINUX

11 linux bash shell

我尝试用它cat然后在我输入我添加的第二个文件| head -$line | tail -1但是它不起作用,因为它cat首先执行.

有任何想法吗?我需要用cat其他东西做.

Jon*_*ler 21

我可能会用sed这个工作:

line=3
sed -e "${line}r file2" file1
Run Code Online (Sandbox Code Playgroud)

如果您要覆盖file1并且您有GNU sed,请添加该-i选项.否则,写入临时文件,然后将临时文件复制/移动到原始文件上,根据需要清理(这是trap下面的内容).注意:在文件上复制临时文件会保留链接; 移动不会(但更快,特别是如果文件很大).

line=3
tmp="./sed.$$"
trap "rm -f $tmp; exit 1" 0 1 2 3 13 15
sed -e "${line}r file2" file1 > $tmp
cp $tmp file1
rm -f $tmp
trap 0
Run Code Online (Sandbox Code Playgroud)


gni*_*urf 7

只是为了好玩,只因为我们都喜欢ed,标准编辑器,这是一个ed版本.它非常有效(ed是一个真正的文本编辑器)!

ed -s file2 <<< $'3r file1\nw'
Run Code Online (Sandbox Code Playgroud)

如果行号存储在变量中,line则:

ed -s file2 <<< "${line}r file1"$'\nw'
Run Code Online (Sandbox Code Playgroud)

只是为了取悦Zack,这是一个版本较少的版本,如果你不喜欢bash(个人而言,我不喜欢管道和子壳,我更喜欢herestrings,但是嘿,正如我所说,这只是为了取悦Zack):

printf "%s\n" "${line}r file1" w | ed -s file2
Run Code Online (Sandbox Code Playgroud)

或者(为了取悦Sorpigal):

printf "%dr %s\nw" "$line" file1 | ed -s file2
Run Code Online (Sandbox Code Playgroud)

正如Jonathan Leffler在评论中提到的,如果您打算在脚本中使用此方法,请使用heredoc(通常效率最高):

ed -s file2 <<EOF
${line}r file1
w
EOF
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

PS如果您觉得需要表达自己的驾驶方式(ed标准编辑器),请不要犹豫,发表评论.