简体   繁体   English

Unix Bash-如何在文件名后立即打印字数,而无需换行

[英]Unix Bash- How to print word count immediately after file name without line break

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 foo.txt

500 500

bar.txt bar.txt

210 210

... What it should be: ...应该是什么:

foo.txt 500 foo.txt 500

bar.txt 210 ... bar.txt 210 ...

What I am expecting the answer to look like: wc -l | 我期望答案看起来像什么:wc -l | awk {something} 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). 同样,对总数的限制也很薄弱,对于名为“ totalrash.txt ”的文件来说,它会中断很多(感谢@rici的精明批评)。

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: 您可以使用一个简单的循环,然后awk:

for i in *.txt 为我在* .txt中
do
awk 'END {printf "%s %d\\n", FILENAME, NR}' $i awk'END {printf“%s%d \\ n”,FILENAME,NR}'$ i
done 做完了

or, you could use wc -l like this: 或者,您可以像这样使用wc -l:

wc -l *.txt | wc -l * .txt | awk '$2 != "total" {printf "%s %d\\n", $2, $1}' awk'$ 2!=“总计” {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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM