我认为必须有一种更简单的方法来实现这一点。
我有这样的文件(由ls返回):
./my_file_0.txt
./the_file_1.txt
./my_file_2.txt
./a_file_3.txt
我目前正在使用:
grep -l "string" ./*_file_*.txt | cut -c 3- | cut -d "." -f1 | cut -d "_" -f1,3 | tr -s "_" " "
要获得正确的输出,请执行以下操作:
my 0
the 1
my 2
a 3
虽然它有效,但我这样做很困难吗?这似乎很麻烦...
谢谢!
你可以
先做你的 grep,然后通过管道将grep -l
输出传送到:
awk -F'[./]|_file_' '{print $3,$4}'
或
sed 's#.[^.]*$##;s#./##;s#_file_# #'
例如
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