我需要使用awk从一个文件中插入行到另一个文件(pattern_string)开始。我不需要sed的解决方案。
inputfiles: file1.txt and file2.txt
outputfile: mergedfile.txt
示例文件:
FILE1.TXT
1
2
pattern_string
7
8
9
FILE2.TXT
3
4
5
6
预期的合并文件mergedfile.txt
1
2
pattern_string
3
4
5
6
7
8
9
答案 0 :(得分:2)
最好使用sed
来实现此目的。使用/r
,您可以在匹配pattern_string
时阅读文件:
sed "/pattern_string/r fle2.txt" file1.txt
返回:
1
2
pattern_string
3
4
5
6
7
8
9
答案 1 :(得分:1)
编辑第一个避免Ed Morton指出问题的解决方案
awk 'FNR==NR {a[i++]=$0;next} /pattern_string/ {print; for(i=0;i in a;i++) print a[i];next}1' file2 file1
输出:
1
2
pattern_string
3
4
5
6
7
8
9
将file2读入数组,然后开始打印file1直到模式匹配,然后打印数组内容,并继续打印file1。
<小时/> 或者您可以使用:
awk 'BEGIN {
while((getline<"file1") == 1) {
print;
if($0 ~ /pattern_string/) {
while((getline<"file2") == 1) print;
close("file2");
}
}
close("file1");
}'
哪个输出相同,但没有使用数组来存储file2
答案 2 :(得分:0)
如果包含的文件也可以将行替换为其他文件,则此脚本不仅会扩展说出&#34; include子文件&#34;的所有行,而是将结果写入tmp文件,重置ARGV [1](最高级别输入文件)而不重置ARGV [2](tmp文件),然后让awk对扩展结果进行任何正常记录解析,因为现在存储在tmp文件。如果您不需要,只需执行&#34; print&#34; to stdout并删除对tmp文件或ARGV [2]的任何其他引用。
awk '
function read(file, rec, arr) {
while ( (getline rec < file) > 0) {
split(rec,arr)
if (arr[1] == "include") {
read(arr[2])
} else {
print rec > ARGV[2]
}
}
close(file)
}
BEGIN{
read(ARGV[1])
ARGV[1]=""
close(ARGV[2])
}
1
' file tmp