依序將與模式相符的行替換為另一個文件中的行

依序將與模式相符的行替換為另一個文件中的行

我想從另一個文件中按順序替換與一個文件中的模式匹配的行,例如,給定:

文件1.txt:

aaaaaa
bbbbbb
!! 1234
!! 4567
ccccc
ddddd
!! 1111

我們喜歡替換以 !! 開頭的行與此文件的行:

文件2.txt:

first line
second line
third line

所以結果應該是:

aaaaaa
bbbbbb
first line
second line
ccccc
ddddd
third line

答案1

可以輕鬆完成awk

awk '
    /^!!/{                    #for line stared with `!!`
        getline <"file2.txt"  #read 1 line from outer file into $0 
    }
    1                         #alias for `print $0`
    ' file1.txt

其他版本

awk '
    NR == FNR{         #for lines in first file
        S[NR] = $0     #put line in array `S` with row number as index 
        next           #starts script from the beginning
    }
    /^!!/{             #for line stared with `!!`
        $0=S[++count]  #replace line by corresponded array element
    }
    1                  #alias for `print $0`
    ' file2.txt file1.txt

答案2

GNU sed, 類似於awk+getline

$ sed -e '/^!!/{R file2.txt' -e 'd}' file1.txt
aaaaaa
bbbbbb
first line
second line
ccccc
ddddd
third line
  • R一次給一行
  • 順序很重要,先R在後d


perl

$ < file2.txt perl -pe '$_ = <STDIN> if /^!!/' file1.txt
aaaaaa
bbbbbb
first line
second line
ccccc
ddddd
third line
  • 將帶有替換行的檔案作為標準輸入傳遞,以便我們可以使用<STDIN>filehandle讀取它
  • 如果找到匹配的行,則替換$_為標準輸入中的行

相關內容