我想在两种模式之间添加一些大代码:
FILE1.TXT
This is text to be inserted into the File.
infile.txt
Some Text here
First
Second
Some Text here
我想在 First 和 Second 之间添加 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
答案 0 :(得分:7)
由于/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 adding text before some pattern中建议的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
答案 1 :(得分:1)
我想你可以试试这个
$ sed -n 'H;${x;s/Second.*\n/This is text to be inserted into the File\
&/;p;}' infile.txt
答案 2 :(得分:1)
awk
味道:
awk '/First/ { print $0; getline < "File1.txt" }1' File2.txt
答案 3 :(得分: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