簡體   English   中英

使用sed命令在File中的兩個模式之間添加文本

[英]Add text between two patterns in File using sed command

我想在兩個模式之間添加一些大代碼:

FILE1.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 

由於/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 -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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM