Domanda

I am thinking there has to be a simpler way to do this.

I have files like this (as returned by ls):

./my_file_0.txt
./the_file_1.txt
./my_file_2.txt
./a_file_3.txt

I am currently using:

grep -l "string" ./*_file_*.txt | cut -c 3- | cut -d "." -f1 | cut -d "_" -f1,3 | tr -s "_" " "

to get the correct output:

my 0
the 1
my 2
a 3

Although it works, am I doing this the hard way? This seems cumbersome...

Thanks!

È stato utile?

Soluzione

you can do your grep first, and then pipe the grep -l output to:

awk -F'[./]|_file_' '{print $3,$4}'

or

sed 's#\.[^.]*$##;s#./##;s#_file_# #'

e.g.

kent$  echo "./my_file_0.txt
./the_file_1.txt
./my_file_2.txt
./a_file_3.txt"|awk -F'[./]|_file_' '{print $3,$4}'
my 0
the 1
my 2
a 3

kent$  echo "./my_file_0.txt
./the_file_1.txt
./my_file_2.txt
./a_file_3.txt"|sed 's#\.[^.]*$##;s#./##;s#_file_# #'         
my 0
the 1
my 2
a 3
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top