Smith Dwayne
Smith Dwayne

Reputation: 2807

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?

Upvotes: 0

Views: 6395

Answers (1)

Allan
Allan

Reputation: 12438

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

Upvotes: 1

Related Questions