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

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

#!/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的其他内容。
dest_file_dir/dest_file
源文件的现有内容
目标文件的现有内容


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

姜源Jerry

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值