bash 使用文件名列表填充和读取数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6648549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
populate and read an array with a list of filenames
提问by Fabio B.
Trivial question.
琐碎的问题。
#!/bin/bash
if test -z ""
then
echo "No args!"
exit
fi
for newname in $(cat ); do
echo $newname
done
I want to replace that echo inside the loop with array populationcode. Then, after the loop ends, I want to read the arrayagain and echo the contents. Thanks.
我想用数组填充代码替换循环内的回声。然后,在循环结束后,我想再次读取数组并回显内容。谢谢。
回答by Diego Sevilla
If the file, as your code shows, has a set of files, each in one line, you can assign the value to the array as follows:
如果文件(如您的代码所示)有一组文件,每个文件在一行中,您可以将值分配给数组,如下所示:
array=(`cat `)
After that, to process every element you can do something like:
之后,要处理每个元素,您可以执行以下操作:
for i in ${array[@]} ; do echo "file = $i" ; done
回答by l0b0
declare -a files
while IFS= read -r
do
files+=("$REPLY") # Array append
done < ""
echo "${files[*]}" # Print entire array separated by spaces
catis not neededfor this.
cat不需要这个。
回答by Laimoncijus
#!/bin/bash
files=( )
for f in $(cat ); do
files[${#files[*]}]=$f
done
for f in ${files[@]}; do
echo "file = $f"
done

