8

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

文件1.txt

This is text to be inserted into the File.

infile.txt

Some Text here
First
Second
Some Text here

我想在FirstSecond之间添加File1.txt内容:

期望的输出:

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

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

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

4 回答 4

10

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

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

你可以在这里找到一些信息:Reading in a file with the 'r' command

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

无论字符的大小写如何,要执行此操作,请使用 Use sed with ignore case while add text before some patternI中建议的标记:

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
于 2013-05-30T12:40:24.603 回答
1

我想你可以试试这个

$ sed -n 'H;${x;s/Second.*\n/This is text to be inserted into the File\
&/;p;}' infile.txt
于 2013-05-30T12:39:48.817 回答
1

awk味道:

awk '/First/ { print $0; getline < "File1.txt" }1' File2.txt
于 2013-05-30T12:52:26.373 回答
0

这是我为从 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 -v i=$k -v j=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 -v i=$((k+1)) -v j=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 -v i=$k -v j=2 -v h=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
于 2017-07-26T15:52:12.497 回答