我有一个名为c的数组。 它的元素是在当前目录中找到的文件名。 我如何在他们自己的行上列出他们之前的数字? 例如:
1. aaa 2. filename2 3. bbb 4. asdf我现在的代码只是在自己的行上打印每个文件。 喜欢:
aaa filename2 bbb asdf我的代码如下:
#!/bin/bash c=( $(ls --group-directories-first $*) ) printf '%s\n' "${c[@]}"I have an array named c. Its elements are filenames found in the current directory. How do I list them on their own line with a number before? For example:
1. aaa 2. filename2 3. bbb 4. asdfThe code I have now just prints each file on its own line. Like:
aaa filename2 bbb asdfMy code is below:
#!/bin/bash c=( $(ls --group-directories-first $*) ) printf '%s\n' "${c[@]}"最满意答案
从数组c开始,这里有三种方法:
用cat -n
cat实用程序将编号输出行:
$ cat -n < <(printf "%s\n" "${c[@]}") 1 aaa 2 filename2 3 bbb 4 asdf使用bash
此方法使用shell算法对行进行编号:
$ count=0; for f in "${c[@]}"; do echo "$((++count)). $f"; done 1. aaa 2. filename2 3. bbb 4. asdf使用nl
在评论中,twalberg建议使用nl :
$ nl < <(printf "%s\n" "${c[@]}") 1 aaa 2 filename2 3 bbb 4 asdf实用程序nl具有许多选项,用于精确控制编辑的编排方式,包括例如左/右对齐,包含前导零。 见man nl 。
Starting with array c, here are three methods:
Using cat -n
The cat utility will number output lines:
$ cat -n < <(printf "%s\n" "${c[@]}") 1 aaa 2 filename2 3 bbb 4 asdfUsing bash
This method uses shell arithmetic to number the lines:
$ count=0; for f in "${c[@]}"; do echo "$((++count)). $f"; done 1. aaa 2. filename2 3. bbb 4. asdfUsing nl
In the comments, twalberg suggests the use of nl:
$ nl < <(printf "%s\n" "${c[@]}") 1 aaa 2 filename2 3 bbb 4 asdfThe utility nl has a number of options for controlling exactly how you want the numbering done including, for example, left/right justification, inclusion of leading zeros. See man nl.
更多推荐
发布评论