当使用-A或-B标志(一次匹配返回多行)时,我无法弄清楚如何从grep输出进行匹配。我不反对为此使用awk,但这将用于检查多个大文件,因此执行时间越短越好。
我认为可以通过使用grep的--group-separator标志并将IFS设置为相同字符来实现此目的,但这似乎并非如此。
$ grep --group-separator=@ -B2 'locked' thisisatest | while IFS=@ read -r match; do
echo "a"
echo "${match}"
done
a
this is a test file asdflksdklsdklsdkl.txt
a
this is meaningless
a
this is locked
a
a
this is a test file basdflksdklsdklsdkl.txt
a
this is meaningless
a
this is locked
$ cat thisisatest
this is a test file asdflksdklsdklsdkl.txt
this is meaningless
this is locked
j
j
j
j
j
this is a test file basdflksdklsdklsdkl.txt
this is meaningless
this is locked
我希望在整个比赛之前和之后都打印“ a”,例如:
a
this is a test file asdflksdklsdklsdkl.txt
this is meaningless
this is locked
a
答案 0 :(得分:0)
更改$IFS
可控制read
如何将行拆分为字段。您一次只能填写一个字段($match
),因此字段定界符无关紧要。改为更改行定界符:使用read -d
。
grep ... | while read -d@ -r match; do