我正在尝试将result=$(ls -Q)
返回的所有项目放到数组中。
如果我回复result
,它看起来像这样:"folder2" "folder space" "test 123"
。请注意,某些项目包含空格。
如何将每个项目放在数组中的引号(引号必须保留在那里)。我想要的输出是:
echo ${ARRAY[0]} --> "folder2"
echo ${ARRAY[1]} --> "folder space"
echo ${ARRAY[2]} --> "test 123"
我怎样才能做到这一点?
答案 0 :(得分:3)
像这样使用filename expansion:
ARRAY=(*)
示例:
mkdir test
cd test
# Create file with space in name
touch 'foo bar'
# Create file with newline in name
touch 'hello
world'
files=(*)
for file in "${files[@]}" ; do
echo "name: ${file}"
done
输出:
name: foo bar
name: hello
world
答案 1 :(得分:0)
不要解析ls的输出。即使使用-Q,它也已经坏了。在我的有毒文件名目录中,我得到了这个:
res=(*)
for f in "${res[@]}"; do echo "file: $f"; done
file: 1 file.tar.gz
file: 2 file.tar.gz
file: 3 file.tar.gz
file: 4 file.tar.gz
file: 5 file.tar.gz
file: abc3<foo.mp3
file: bb bb
file: dd dd
file: ff ff
file: file-mit"Quote"
file: m d.sh
file: regex=*a*
file: zeilen
umbruch.zip
我的第一个回答和评论是错误的:
ls -Q
"1 file.tar.gz" "3 file.tar.gz" "5 file.tar.gz" "bb bb" "ff ff" "m d.sh" "zeilen\numbruch.zip"
"2 file.tar.gz" "4 file.tar.gz" "abc3<foo.mp3" "dd dd" "file-mit\"Quote\"" "regex=*a*"
result=($(ls -Q))
for f in ${result[@]}; do echo "file $f"; done
file "1
file file.tar.gz"
file "2
file file.tar.gz"
file "3
file file.tar.gz"
file "4
file file.tar.gz"
file "5
file file.tar.gz"
file "abc3<foo.mp3"
file "bb
file bb"
file "dd
file dd"
file "ff
file ff"
file "file-mit\"Quote\""
file "m
file d.sh"
file "regex=*a*"
file "zeilen\numbruch.zip"