元素中带有空格的 Bash 数组 [英] Bash array with spaces in elements

查看:38
本文介绍了元素中带有空格的 Bash 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用我的相机中的文件名在 bash 中构造一个数组:

I'm trying to construct an array in bash of the filenames from my camera:

FILES=(2011-09-04 21.43.02.jpg
2011-09-05 10.23.14.jpg
2011-09-09 12.31.16.jpg
2011-09-11 08.43.12.jpg)

如您所见,每个文件名中间都有一个空格.

As you can see, there is a space in the middle of each filename.

我尝试将每个名称用引号括起来,并用反斜杠转义空格,但都不起作用.

I've tried wrapping each name in quotes, and escaping the space with a backslash, neither of which works.

当我尝试访问数组元素时,它继续将空格视为元素分隔符.

When I try to access the array elements, it continues to treat the space as the elementdelimiter.

如何正确捕获名称中包含空格的文件名?

How can I properly capture the filenames with a space inside the name?

推荐答案

我认为问题可能部分与您访问元素的方式有关.如果我在 $FILES 中为 elem 做一个简单的 ,我会遇到和你一样的问题.但是,如果我通过它的索引访问数组,就像这样,如果我以数字或转义方式添加元素,它就会起作用:

I think the issue might be partly with how you're accessing the elements. If I do a simple for elem in $FILES, I experience the same issue as you. However, if I access the array through its indices, like so, it works if I add the elements either numerically or with escapes:

for ((i = 0; i < ${#FILES[@]}; i++))
do
    echo "${FILES[$i]}"
done

$FILES 的任何这些声明都应该有效:

Any of these declarations of $FILES should work:

FILES=(2011-09-04\ 21.43.02.jpg
2011-09-05\ 10.23.14.jpg
2011-09-09\ 12.31.16.jpg
2011-09-11\ 08.43.12.jpg)

FILES=("2011-09-04 21.43.02.jpg"
"2011-09-05 10.23.14.jpg"
"2011-09-09 12.31.16.jpg"
"2011-09-11 08.43.12.jpg")

FILES[0]="2011-09-04 21.43.02.jpg"
FILES[1]="2011-09-05 10.23.14.jpg"
FILES[2]="2011-09-09 12.31.16.jpg"
FILES[3]="2011-09-11 08.43.12.jpg"

这篇关于元素中带有空格的 Bash 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆