简体   繁体   中英

Formatting grep output in command line

I used this following grep command to search a text in a multiple files.

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:

$ 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:

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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