将每一行存储在单个数组字段上

时间:2022-12-13 20:50:45

My problem is:

我的问题是:

In my bash script the command.

在我的bash脚本中命令。

ls -d */ | sed 's#/##'

shows me all folders in current path like:

显示当前路径中的所有文件夹,如:

dir1
new folder2
folder3
new directory 4

now i need to store those in a array but the problem is that "new folder2" will cover 2 array fields, i need to store every line in a single field. So that:

现在我需要将它们存储在一个数组中,但问题是“new folder2”将覆盖2个数组字段,我需要将每一行存储在一个字段中。以便:

var[0] = "dir1"
var[1] = "new folder2"
var[2] = "folder3"
var[3] = "new directory 4"

How to achieve that?

怎么实现呢?

1 个解决方案

#1


2  

You need an array with each folder of the current directory. It's really that simple:

您需要一个包含当前目录的每个文件夹的数组。它真的很简单:

shopt -s nullglob
var=(*/)

If you then decide you need to strip the trailing slash from the array members, it's better to do so when you iterate over them, or output them to the user. As long as you work with globs – which is what */ is – you're going to be pretty safe without the need to manipulate strings.

如果您确定需要从数组成员中删除尾部斜杠,则最好在迭代它们时将其删除,或将它们输出给用户。只要你使用globs - 这就是* /是 - 你将非常安全而不需要操纵字符串。

Good to read:

好读:

#1


2  

You need an array with each folder of the current directory. It's really that simple:

您需要一个包含当前目录的每个文件夹的数组。它真的很简单:

shopt -s nullglob
var=(*/)

If you then decide you need to strip the trailing slash from the array members, it's better to do so when you iterate over them, or output them to the user. As long as you work with globs – which is what */ is – you're going to be pretty safe without the need to manipulate strings.

如果您确定需要从数组成员中删除尾部斜杠,则最好在迭代它们时将其删除,或将它们输出给用户。只要你使用globs - 这就是* /是 - 你将非常安全而不需要操纵字符串。

Good to read:

好读: