[英]Filter a command's output by occurrences of a certain character?
So say I have a command, such as ls
. 假设我有一个命令,例如ls
。 And the output is large, and I want to filter it by the number of occurrences of the character ':'. 而且输出很大,我想按字符“:”的出现次数对其进行过滤。 The occurrences wouldn't need to be consecutive, they'd simply need to occur. 这些事件不必是连续的,它们只需要发生即可。 Any line with ten or more of these occurrences should be sent to the output. 具有十个或更多这些事件的任何行都应发送到输出。 Is there a way to do this? 有没有办法做到这一点? I was thinking of doing a python script, and making it a command, like this , but I wasn't sure how I'd format the script, and what I could and couldn't do in terms of piping output from a previous command into this new script/command. 我想在做一个python脚本,并使其成为一个命令,像这样 ,但我不知道我怎么会格式化剧本,我能做和不能在管道输出方面,从以前的命令做到这个新的脚本/命令中。
A shell solution would involve calling awk
. Shell解决方案将涉及调用awk
。
ls | awk -F: 'NF<9'
This reads the standard-out from ls
sends it to a pipe, and awk
splits each line into fields based on :
. 这将从ls
读取标准输出,并将其发送到管道,并且awk
将每行拆分为多个字段:
The NF
mean Number of Fields. NF
平均场数。 When NF
is greater than 9
, the record will be printed. 当NF
大于9
,将打印记录。
you can extend this to filter on any number by passing in a variable 您可以通过传入变量将其扩展为过滤任何数字
ls | awk -F: -v minCnt=10 'NF<=minCnt`
IHTH IHTH
Using extended regular expressions: 使用扩展的正则表达式:
ls | egrep '(:.*){10,}'
Example, from man bash
, show all lines with 15 or more " e "s, then highlight them in color: 例如,在man bash
,显示所有包含15个或更多“ e ”的行,然后以彩色突出显示它们:
COLUMNS=80 man bash | egrep --color '(e.*){15,}' | grep --color e
Output, (the colored part is in boldface): 输出(彩色部分为粗体):
gr e at e r than 9 ar e r e pr e s e nt e d by th e low e rcas e l e tt e rs, th e upp e rcas e GRË在比由前作 低辐射 RCASËL E TTëRS,当前作 UPPËRCASë9 ARËřËPR(E S)ÊNTËdËř
You can read from standard input, filter and write to standard output: 您可以从标准输入中读取,过滤并写入标准输出:
# script.py
import sys
for line in sys.stdin:
if line.count(':') >= 10:
sys.stdout.write(line)
Call: 呼叫:
> ls | python script.py
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.