ls在当前目录上运行命令并获取输出:
$ ls
Applications Documents Library Music Public
Desktop Downloads Movies Pictures
Run Code Online (Sandbox Code Playgroud)
我想列举它们,如:
1. Applications
2. Desktop
3. Documents
4. Downloads
5. Library
6. Movies
7. Music
8. Pictures
9. Public
Run Code Online (Sandbox Code Playgroud)
这可以通过less中间方式实现
ls | less -N
Run Code Online (Sandbox Code Playgroud)
如何以直接的方式枚举它们?
αғs*_*нιη 18
或者干脆做:
ls -b |nl -s '. ' -w 1
1. a\ file\ with\ nonewline
2. a\ file\ with\nnewline
3. a\ file\ with\ space
4. afile
Run Code Online (Sandbox Code Playgroud)
来自man nl:
-s, --number-separator=STRING
add STRING after (possible) line number
-w, --number-width=NUMBER
use NUMBER columns for line numbers
Run Code Online (Sandbox Code Playgroud)
pa4*_*080 13
您应该将 的输出通过管道ls传输到另一个命令。我的建议是使用awk在这样:
$ ls -b --group-directories-first | awk '{print NR ". " $0}'
1. dir1
2. dir2
3. dir3
4. z-dir1
5. z-dir2
6. z-dir3
7. file1
8. file2
9. file3
10. file4
11. file5
12. file6
13. file7
14. file\nnewline
Run Code Online (Sandbox Code Playgroud)
请注意,该文件的名称中file\nnewline包含换行符\n,该字符被选项转义-b。
该选项--group-directories-first将在文件之前输出目录。
另一种可能的方法是使用 for 循环(但在这种情况下,将目录放置在列表中会变得更加困难):
n=1; for i in *; do echo $((n++)). $i; done
Run Code Online (Sandbox Code Playgroud)
αғs*_*нιη 11
如果只是显示一个数字,那么您有以下几种选择以及您的less -N方式:
$ ls |cat -n
$ ls |nl
Run Code Online (Sandbox Code Playgroud)
如果您想要自定义输出编号,那么我建议您使用find并执行您想要打印的任何内容:
find . -exec bash -c 'for fnd; do printf "%d. %s\n" "$((++i))" "$fnd"; done ' _ {} +
Run Code Online (Sandbox Code Playgroud)
POSIXly,你会这样做:
find . -exec sh -c 'for fnd; do i=$((i+1)); printf "%d.\t%s\n" "$i" "$fnd"; done ' _ {} +
Run Code Online (Sandbox Code Playgroud)