Is it possible to grep only one column and print other SELECTED output at the same time
Title my be ambiguous. Here's an example of what I'm asking.
#ls -l
prints me ou开发者_高级运维t something like this
-rw-r--r-- 1 root root 5110 2011-10-08 19:36 test.txt
-rw-r--r-- 1 root root 5111 2011-10-08 19:38 test.txt
-rw-r--r-- 1 root root 5121 2011-10-08 19:36 5110.txt
-rw-r--r-- 1 root root 5122 2011-10-08 19:38 5111.txt
Say I wanted to use grep to find all filenames containing '511'
and print out the size/filename of the file.
How do I grep for filenames '511'
, still print the filesize, and not have the output contain the top two rows.
thank you very much SO, reading man pages hasn't helped me on this one.
You can use awk
for this:
pax:~$ echo '
-rw-r--r-- 1 root root 5110 2011-10-08 19:36 test.txt
-rw-r--r-- 1 root root 5111 2011-10-08 19:38 test.txt
-rw-r--r-- 1 root root 5121 2011-10-08 19:36 5110.txt
-rw-r--r-- 1 root root 5122 2011-10-08 19:38 5111.txt
' | awk '{if (substr($8,1,3)=="511"){print $5" "$8}}'
5121 5110.txt
5122 5111.txt
It simply checks field 8 (the filename) to see if it starts with "511" and, if so, prints out fields 5 and 8, the size and name.
find . -name '*511*' -printf "%s\t%p\n"
If it's just the filename you want to filter on, why do you list other files in the first place?
ls -l *511* | cut -c23-30,48-
or even with awk
;
ls -l *511* | awk '{ $1 = $2 = $3 = $4 = $6 = $7 = ""; print }'
However, the output from ls
is not entirely robust, so you should avoid processing it directly.
perl -le 'for (@ARGV) { print ((stat($_))[7], " $_") }' *511*
The stat()
system call returns the raw information displayed by ls
in a machine-readable format. Any tool which gives you access to this information is fine; it doesn't have to be Perl.
You can bypass ls
and just use bash
's filename glob
:
for f in 511*
do
echo $f $(stat --format '%s' $f)
done
精彩评论