使用awk从stdin或文件中读取 [英] Reading from stdin OR file using awk
问题描述
所以这是到目前为止的代码:
So here's my code so far:
awk '{++a[length()]} END{for (i in a) print i, a[i]}' <$1 | sort -n
从文本文件中读取行的长度,然后输出行的长度,然后输出多少行具有相同的长度.
which reads the lengths of lines from a text file, and outputs the length of the line, and then how many lines have the same length.
所以输入:
hello
guys
hows
it
going
将输出:
2 1
4 2
5 2
我希望它也能够具有stdin,因此我将能够运行命令"./script filename.txt",也能够使用标准输入来运行该命令.
I want it to be able to have stdin too, so i will be able to run the command "./script filename.txt" and also be able to run the command using standard input.
有什么方法可以通过while循环完成吗?我试图做类似的事情:
Is there any way this can be done with a while loop? I have tried to do something similar to:
while read line
do
awk '{++a[length()]} END{for (i in a) print i, a[i]}' <${1:-/dev/stdin} | sort -n
done <${1:-/dev/stdin}
但似乎什么都无法正常工作...
but nothing seems to be working correctly...
有什么想法吗?
推荐答案
您可以使用破折号(-
)作为文件名,awk将其理解为使用stdin作为要解析的文件.例如:
You may use the dash (-
) as the filename, awk understands it as using stdin as the file to parse. For example:
awk '{++a[length()]} END{for (i in a) print i, a[i]}' -
另外,通过完全不指定文件名,awk也使用标准输入
Also, by not specifying a filename at all, awk also uses stdin
awk '{++a[length()]} END{for (i in a) print i, a[i]}'
请注意,您可以将它们混合使用.以下将按此顺序处理file1.txt,stdin和file2.txt:
And note that you can mix them both. The following will process file1.txt, stdin and file2.txt in that order:
awk '{++a[length()]} END{for (i in a) print i, a[i]}' file1.txt - file2.txt
这篇关于使用awk从stdin或文件中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!