使用sed命令在两个模式之间添加文本

我想在两个模式之间添加一些大的代码:

FILE1.TXT

This is text to be inserted into the File. 

infile.txt

 Some Text here First Second Some Text here 

我想在第一个第二个之间添加File1.txt内容:

期望的输出:

 Some Text here First This is text to be inserted into the File. Second Some Text here 

我可以用sed命令search两种模式,但我不知道如何在它们之间添加内容。

 sed '/First/,/Second/!d' infile 

由于/r代表读取文件 ,使用:

 sed '/First/r file1.txt' infile.txt 

你可以在这里找到一些信息: 用'r'命令读入一个文件 。

在就地版本中添加-i (即sed -i '/First/r file1.txt' infile.txt )。

要执行此操作,不管字符的情况如何,在使用sed with ignore case时建议使用 I标记, 同时在某种模式之前添加文本 :

 sed 's/first/last/Ig' file 

如注释所示,上述解决方案只是在给定的字符串之后打印一个模式,而不考虑第二个模式。

要做到这一点,我会去找一个带有标志的awk:

 awk -v data="$(<patt_file)" '/First/ {f=1} /Second/ && f {print data; f=0}1' file 

鉴于这些文件:

 $ cat patt_file This is text to be inserted $ cat file Some Text here First First Second Some Text here First Bar 

让我们运行命令:

 $ awk -v data="$(<patt_file)" '/First/ {f=1} /Second/ && f {print data; f=0}1' file Some Text here First # <--- no line appended here First This is text to be inserted # <--- line appended here Second Some Text here First # <--- no line appended here Bar 

我想你可以试试这个

 $ sed -n 'H;${x;s/Second.*\n/This is text to be inserted into the File\ &/;p;}' infile.txt 

awk风味:

 awk '/First/ { print $0; getline < "File1.txt" }1' File2.txt 

下面是我写的从patt_file插入模式的bash代码。 本质上不得不使用uniq删除一些重复的数据,然后添加一些东西回来。我复制我需要放回使用lineNum值的东西,将其保存到past_file。 然后匹配patMatch在我添加的东西的文件。

  #This pulls the line number from row k, column 2 of the reduced repitious file lineNum1=$(awk -vi=$k -vj=2 'FNR == i {print $j}' test.txt) #This pulls the line number from row k + 1, coulmn 2 of the reduced repitious file lineNum2=$(awk -vi=$((k+1)) -vj=2 'FNR == i {print $j}' test.txt) #This pulls fields row 4, 2 and 3 column into with tab spacing (important) from reduced repitious file awk -vi=$k -vj=2 -vh=3 'FNR == i {print $j" "$h}' test.txt>closeJ.txt #This substitutes all of the periods (dots) for \. so that sed will match them patMatch=$(sed 's/\./\\./' closeJ.txt) #This Selects text in the full data file between lineNum1 and lineNum2 and copies it to a file awk -v awkVar1=$((lineNum1 +1)) -v awkVar2=$((lineNum2 -1)) 'NR >= awkVar1 && NR <= awkVar2 { print }' nice.txt >patt_file.txt #This inserts the contents of the pattern matched file into the reduced repitious file #The reduced repitious file will now grow sed -i.bak "/$patMatch/ r "patt_file.txt"" test.txt