如何解决grep -B 1是否有其他选择,因为我不能将grep与-B一起使用来获取o / p awk脚本说明
我在MacOS上的grep不支持GNU grep的-B count
选项。我需要以下命令的替代方法:
while read x; do
find . -name \*$x\* -exec cat {} + |
grep -i -B 1 "failed with status"
done < x
下面是我需要的命令输出:
/phobos/user/jwang223/cdjic_mailservice restoring...
Backup failed with status 70.
解决方法
grep的
-B在while循环中也可以正常工作。请重新检查一次格式。
cat boo
a test line
failed with status
some random text
find . -name *b* -exec cat {} \; | grep -B 1 'failed with status'
a test line
failed with status
cat x
boo
while read x; do find . -name \*$x\* -exec cat {} + | grep -i -B 1 "failed with status" ;done < x
a test line
failed with status
,
尝试awk
。
find . -name "*$x*" -exec cat {} + |
awk 'length(prev) != 0 && tolower($0) ~ /failed with status/{ print prev; print } { prev=$0 }'
我猜也sed
:
sed -n '1{h;b;}; H; y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/; /failed with status/{ x; p; s/.*//; n; h; b; }; x; s/[^\n]*\n//; x'
,
在评论中,您提到了该问题的两个重要线索:
-
您似乎在服务器上运行命令(请参见here)
这是不可能的,因为我是在没有root访问权限的服务器主机上运行它的。
-
您提到以下错误(请参见here)
grep: illegal option -- B Usage: grep [-c|-l|-q] -bhinsvw pattern file
这使我相信,您正在OSX上运行命令不是,而是在HP-UNIX上运行。查看man page表明该版本不支持GNU grep扩展。
您可以使用awk模仿-i -B count
选项:
awk -v c=count -v s="failed with status" '
BEGIN{c=c+1}{a[FNR%c]=$0}
(tolower($0) ~ s){
for(i=(FNR>c)*(FNR-c)+1;i<=FNR;++i) print a[i%c]; print "--"
}'
如果count==1
您可以这样做:
awk '(tolower($0)~/failed with status/){print (FNR>1?p ORS:"") $0}{p=$0}'
,
可以将循环简化为单个awk
(standadr Linux awk / gawk)命令,如下所示:
while read x; do
awk 'BEGINFILE{l = ""} /failed with status/{print FILENAME": "l RS $0}{l = $0}' $(find -name "*$x*")
done < x
请注意,匹配的正则表达式模式区分大小写。像这样更改它以适合您的案例:
/failed with status/
-> /[fF][aA][iI][lL][eE][dD] [wW][iI][tT][hH] [sS][tT][aA][tT][uU][sS]/
。
while read x; do
awk 'BEGINFILE{l = ""} /[fF][aA][iI][lL][eE][dD] [wW][iI][tT][hH] [sS][tT][aA][tT][uU][sS]/{print FILENAME": "l RS $0}{l = $0}' $(find -name "*$x*")
done < x
awk
脚本说明
BEGINFILE {previusLine = ""} # On file reading start,reset variable previusLine
/failed with status/ # On lines mathching regex pattern "failed with status"
{
# print filename prefix + previousLine + newline + current line
print FILENAME ": " previusLine RS $0;
}
{ # On each line
previusLine = $0; # save the current line into variable previusLine
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。