bash 如何枚举文件列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23096884/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:12:50  来源:igfitidea点击:

How to enumerate a list of files

bashawksh

提问by Devavrata

I want to get a numbered list of files, e.g. if I have these files:

我想获得一个编号的文件列表,例如,如果我有这些文件:

a.pdf
b.pdf
c

then it should be listed as:

那么它应该被列为:

1 a.pdf
2 b.pdf
3 c

回答by Devavrata

You can do it two ways:-
1st one :-
ls -1 | awk '{print NR,$0}'

您可以通过两种方式做到这一点:-
第一种:-
ls -1 | awk '{print NR,$0}'

2nd one:-
ls -1 | cat -n
You must prefer 2nd one but choose whatever you like. :-)

第二个:-
ls -1 | cat -n
您必须更喜欢第二个,但可以选择任何您喜欢的。:-)

回答by Devavrata

If you want to avoid parsing the output of ls(which you do), you can do something like this:

如果您想避免解析ls(您所做的)的输出,您可以执行以下操作:

$ counter=1; for f in *; do printf "%2d %s\n" $((counter++)) "$f"; done
 1 a.pdf
 2 b.pdf
 3 c

I only mention this because it's the path for doing more sophisticated things, not just enumerating.

我之所以提到这一点,是因为它是做更复杂的事情的途径,而不仅仅是枚举。

回答by BMW

If your system has command nl, it will be easier. ( I can confirm nlcommand is exist in cygwin, aix and solaris system, then it should be popular command in most unix system)

如果您的系统有 command nl,它会更容易。(我可以确认nl命令存在于cygwin、aix和solaris系统中,那么它应该是大多数unix系统中流行的命令)

ls |nl

回答by Scott Lawrence

You can do this without awk, trivially. ls -1 | cat -n.

你可以不用 awk 就可以做到这一点,很简单。ls -1 | cat -n.

Or, with awk:

或者,使用 awk:

ls -1 | awk '{printf "%d %s\n", NR, 
ls | awk '{print NR, ##代码##}'
;}'

回答by Floris

Not sure why you need to use awkbut here you go:

不知道为什么你需要使用,awk但你去吧:

##代码##

updated$0is better than $1since it will print the entire file name even with spaces (as hinted at by BroSlow)

更新$0$1因为即使有空格也会打印整个文件名(如 BroSlow 所暗示的那样)更好

Note - you do notneed to use the -1flag with lswhen the output is another process - it becomes the default option. Only when you want to force output to the terminal with one file per line do you need to use it.

注-你不是需要使用-1国旗ls时,输出也是一个过程-它成为默认选项。只有当你想强制输出到每行一个文件的终端时,你才需要使用它。