パターンに一致する行を別のファイルの行に順次置き換える

パターンに一致する行を別のファイルの行に順次置き換える

たとえば、次のように、あるファイルのパターンに一致する行を別のファイルから順番に置き換えたいとします。

ファイル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 '
    /^!!/{                    #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

おすすめ記事