Tho*_*hor 6
使用sed
替代(GNU SED):
解析.sed
1h # Save the first line to hold space
2,3 { # On lines 2 and 3
/my pattern/ { # Match `my pattern`
x # If there is a match bring back the first line
p # and print it
:a; n; ba # Loop to the end of the file
}
}
像这样运行它:
sed -snf parse.sed file1 file2 ...
或者作为单线:
sed -sn '1h; 2,3 { /my pattern/ { x; p; :a; n; ba; } }' file1 file2 ...
您可能还想发出文件名,例如使用您的示例数据:
解析2.sed
1h # Save the first line to hold space
2,3 { # On lines 2 and 3
/two/ { # Match `my pattern`
F # Output the filename of the file currently being processed
x # If there is a match bring back the first line
p # and print it
:a; n; ba # Loop to the end of the file
}
}
像这样运行它:
sed -snf parse2.sed file1 file2 | paste -d: - -
输出:
file1:file 1
file2:file 2
Sun*_*eep 6
$ awk 'FNR==2{if(/one/) print line; nextfile} FNR==1{line=$0}' 1.txt 2.txt
file 1
$ awk 'FNR==2{if(/two/) print line; nextfile} FNR==1{line=$0}' 1.txt 2.txt
file 2
FNR
将具有正在读取的当前文件的行号
使用FNR>=2 && FNR<=3
,如果你需要一个行范围
FNR==1{line=$0}
将保存第一行的内容以备将来使用
nextfile
大多数实现都应该支持,但是如果您需要删除它,该解决方案仍然可以工作(虽然速度较慢)
更多推荐
文件,GREP
发布评论