[英]Looping through array of filenames in bash and read them
I have an array that contains paths of files.我有一个包含文件路径的数组。 Each of these files has a single line.
这些文件中的每一个都有一行。 I would like to loop through the array, and for each file read the line in it and store it in a variable.
我想遍历数组,并为每个文件读取其中的行并将其存储在变量中。 I tried this
我试过这个
f1=$1
f2=$2
filenames[0]=${f1}
filenames[1]=${f2}
for filename in "${filenames[@]}"
do
# get the filename
set fl = `basename $filename`
echo ${fl}
# read its contents (one line)
set filecontent = `cat ${fl}`
echo ${filecontent}
done
both echos display blank spaces.两个回声都显示空格。 If I do
如果我做
echo `basename $filename`
it does display the filename.它确实显示文件名。 What is wrong with the loop above?
上面的循环有什么问题?
The basic problem is that you seem to be mixing bash and tcsh syntax -- and just by chance you're using tcsh commands that happen not to be syntax errors in bash, but don't do what you want.基本问题是您似乎混合了 bash 和 tcsh 语法——碰巧您使用的 tcsh 命令恰好不是 bash 中的语法错误,但没有做您想做的事。
This:这个:
set fl = `basename $filename`
is how you'd set $fl
to the basename of $filename
in tcsh.是您如何将
$fl
设置为 tcsh 中$filename
的基本名称。 In bash, however, the set
command is quite different.然而,在 bash 中,
set
命令完全不同。 Since it's not what you need to use here anyway, I won't go into details, but you can read about them here .因为无论如何这不是你需要在这里使用的东西,所以我不会详细介绍 go,但你可以在这里阅读它们。
In bash, the way to set a variable is just在 bash 中,设置变量的方式就是
var=value # NO spaces around the "="
Also, bash, unlike tcsh, has a $(command)
syntax to capture the output of a command, in addition to the older `command`
.此外,与 tcsh 不同,bash 有一个
$(command)
语法来捕获命令的 output,除了旧的`command`
。
So your command所以你的命令
set fl = `basename $filename`
should be应该
fl="$("basename $filename")"
Adding double quotes around both the $filename
reference and the $(...)
command substitution ensures that the shell can handle odd characters in the file name and/or command output.在
$filename
引用和$(...)
命令替换周围添加双引号可确保 shell 可以处理文件名和/或命令 output 中的奇数字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.