简体   繁体   English

在命令行中格式化 grep 输出

[英]Formatting grep output in command line

I used this following grep command to search a text in a multiple files.我使用以下 grep 命令在多个文件中搜索文本。

grep -w 'mytext' *.txt

now my result is,现在我的结果是,

a.txt:mytext          32.15        
b.txt:mytext          27.65        
c.txt:mytext          37.95        

Its like就像是

{filename}.{extension}:{searched-line}

But I want this result like formatted below:但我想要这个结果如下格式:

{filename}:{searched-line}

Just I don't want the extension of that files.只是我不想要那些文件的扩展名。 How can I do that in command line?我怎样才能在命令行中做到这一点?

As said in the comment, you can just pipe it to sed command:正如评论中所说,您可以将其通过管道传输到sed命令:

$ echo -e "a.txt:mytext 32.15\nb.tar.txt:mytext 34.15" | sed 's/\.[^:]*:/:/g'
a:mytext 32.15
b:mytext 34.15


$ echo -e "a.txt:mytext 32.15\nb.tar.txt:mytext 34.15" | sed 's/\.[^.:]*:/:/g'
a:mytext 32.15
b.tar:mytext 34.15

depending on if you want to keep the sub-extension or not.取决于您是否要保留子扩展名。

grep -w 'mytext' *.txt | sed 's/\.[^:]*:/:/g' 

or或者

grep -w 'mytext' *.txt | sed 's/\.[^.:]*:/:/g' 

depending on what you want to achieve.取决于你想要达到的目标。

with awk you can achieve the same:使用awk您可以实现相同的目标:

$echo -e "a.txt:mytext 32.15\nb.tar.txt:mytext 34.15" | awk -F'\\.[^:]*:' 'BEGIN{OFS=":"}{print $1,$2}'
a:mytext 32.15
b:mytext 34.15

or或者

$echo -e "a.txt:mytext 32.15\nb.tar.txt:mytext 34.15" | awk -F'\\.[^.:]*:' 'BEGIN{OFS=":"}{print $1,$2}'                                      
a:mytext 32.15
b.tar:mytext 34.15

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM