I am trying to print filenames in my directory with line/word counts all on one line. The way my output is now:
foo.txt
500
bar.txt
210
... What it should be:
foo.txt 500
bar.txt 210 ...
What I am expecting the answer to look like: wc -l | awk {something}
Here's a simple but flawed way to do it:
wc -l *.txt | awk '$2 != "total" { print $2, $1 }'
However, if you have spaces in the filename, then the above will print the those filenames cut off at the first space. Also, the check for the line with the total is also weak, and breaks spectacularly for a file called "total disaster.txt" (thanks @rici for the shrewd criticism).
Here's a much safer, but a bit longer solution:
wc -l *.txt | awk '{ count = $1; sub("^ *[0-9]+ ", ""); if ($0 != "total") print count, $0 }'
you can use a simple loop, and awk:
for i in *.txt
do
awk 'END {printf "%s %d\\n", FILENAME, NR}' $i
done
or, you could use wc -l like this:
wc -l *.txt | awk '$2 != "total" {printf "%s %d\\n", $2, $1}'
wc -l *.txt | awk '{print $2,$1}'
Does the work for the sample input provided in your question?
Some user is worried about unnecessary space characters in file name
The following should work for you:
for i in *.txt; do echo ${i##*/} `wc -l "$i" | awk '{print $1}'`; done
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.