Mse*_*ade 4 sed awk perl text-processing files
我想从另一个文件中按顺序替换一个文件中匹配模式的行,例如,给定:
文件 1.txt :
aaaaaa
bbbbbb
!! 1234
!! 4567
ccccc
ddddd
!! 1111
Run Code Online (Sandbox Code Playgroud)
我们喜欢替换以 !! 开头的行 使用此文件的行:
文件 2.txt:
first line
second line
third line
Run Code Online (Sandbox Code Playgroud)
所以结果应该是:
aaaaaa
bbbbbb
first line
second line
ccccc
ddddd
third line
Run Code Online (Sandbox Code Playgroud)
Cos*_*tas 10
使用awk可以轻松完成
awk '
/^!!/{ #for line stared with `!!`
getline <"file2.txt" #read 1 line from outer file into $0
}
1 #alias for `print $0`
' file1.txt
Run Code Online (Sandbox Code Playgroud)
其他版本
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
Run Code Online (Sandbox Code Playgroud)