编号数组元素

编程入门 行业动态 更新时间:2024-10-23 15:17:27
编号数组元素 - Bash脚本(Numbering Array Elements - Bash Scripting)

我有一个名为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. asdf

The code I have now just prints each file on its own line. Like:

aaa filename2 bbb asdf

My 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 asdf

Using 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. asdf

Using nl

In the comments, twalberg suggests the use of nl:

$ nl < <(printf "%s\n" "${c[@]}") 1 aaa 2 filename2 3 bbb 4 asdf

The 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.

更多推荐

本文发布于:2023-08-05 20:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1439264.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   元素   编号

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!