【sed】sed -i命令追加多行内容到指定文件的指定位置

本文介绍了如何使用sed的-i命令将一个源文件(src_file)的内容追加到目标文件(dest_file)的第二行开始,同时保持目标文件的其他内容不变。通过示例脚本和运行结果展示,强调了为了正确追加,需按倒序写入追加内容。
摘要由CSDN通过智能技术生成

不多说,直接上我写的一个测试脚本的代码,后面有验证结果。

#!/bin/bash
#for test add content from src_file to dest_file at specified place.
 
echo "hello, begin..."
echo ""
 
src_file=${PWD}"/src_file"
dest_file=${PWD}"/dest_file_dir/dest_file"
 
function for_test ()
{
	test=`sed -i '2i\insert this line' $dest_file`
	echo $test
	echo "****************"
	cat $dest_file
}
 
function add_content_src_to_dest_file ()
{
	delimit_line="==========================================="
 
	# sed -i "2i\\insert line" file 该sed命令使用的是-i参数指定i\选项,在第2行后插入内容
	# 2i\\ 拆解3部分:2为行号,i\为sed行下追加命令,\为转义字符(必须转义读取变量)
	# "" 双引号,保持引号内的字面值,可读\$转义后的变量内容,单引号不行。
	echo $delimit_line | sed -i "2i\\$delimit_line" $dest_file
	cat $src_file | while read line
	do
		echo $line | sed -i "3i\\$line" $dest_file
	done
	
	#cat $dest_file
}
 
 
#for_test
add_content_src_to_dest_file
 
echo ""
echo "hey, end..."
exit 0

将src_file里的文件内容,以dest_file的同样格式一次性放到dest_file的第二行开始的位置,并且不影响dest_file的其他内容。

源文件的现有内容 

[root@web_master test]# cat src_file 
1
2
3
4
5

目标文件的现有内容

[root@web_master test]# cat dest_file_dir/dest_file 
a
b
c
d
e
f

脚本运行后,将src_file所有内容插入在目标文件第2行开始的位置,并加了分割线保持dest_file文件格式。 

[root@web_master test]# sh /data/scripts/insert.sh 
hello, begin...

a
===========================================
5
4
3
2
1
b
c
d
e
f

hey, end...

以上结果发现追加到指定位置是倒叙插入的,为正确追加到指定位置内容不发现改变,只需把追加的内容倒叙写入即可!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值