bash 是否可以仅 grep 一列并同时打印其他 SELECTED 输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7722274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to grep only one column and print other SELECTED output at the same time
提问by glenn Hymanman
Title my be ambiguous. Here's an example of what I'm asking.
标题我模棱两可。这是我要问的一个例子。
#ls -l
prints me out 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.
假设我想使用 grep 查找所有包含文件名的文件 '511'并打印出文件的大小/文件名。
How do I grep for filenames '511', still print the filesize, and not have the output contain the top two rows.
我如何 grep 文件名'511',仍然打印文件大小,并且输出不包含前两行。
thank you very much SO, reading man pages hasn't helped me on this one.
非常感谢您,阅读手册页对我没有帮助。
回答by paxdiablo
You can use awkfor this:
您可以awk为此使用:
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(,1,3)=="511"){print " "}}'
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.
它只是检查字段 8(文件名)以查看它是否以“511”开头,如果是,则打印出字段 5 和 8、大小和名称。
回答by glenn Hymanman
find . -name '*511*' -printf "%s\t%p\n"
回答by tripleee
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;
甚至与awk;
ls -l *511* | awk '{ = = = = = = ""; print }'
However, the output from lsis not entirely robust, so you should avoid processing it directly.
但是, from 的输出ls并不完全可靠,因此您应该避免直接处理它。
perl -le 'for (@ARGV) { print ((stat($_))[7], " $_") }' *511*
The stat()system call returns the raw information displayed by lsin a machine-readable format. Any tool which gives you access to this information is fine; it doesn't have to be Perl.
的stat()系统调用返回由显示的原始信息ls以机器可读的格式。任何可以让您访问此信息的工具都可以;它不必是 Perl。
回答by Brian Cain
You can bypass lsand just use bash's filename glob:
您可以绕过ls并仅使用bash的文件名glob:
for f in 511*
do
echo $f $(stat --format '%s' $f)
done

