天天看点

【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的其他内容。

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

源文件的现有内容 

[[email protected]_master test]# cat src_file 
1
2
3
4
5
           

目标文件的现有内容

[[email protected]_master test]# cat dest_file_dir/dest_file 
a
b
c
d
e
f
           

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

[[email protected]_master test]# sh /data/scripts/insert.sh 
hello, begin...

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

hey, end...
           

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