[英]Looping through array of filenames in bash and read them
我有一個包含文件路徑的數組。 這些文件中的每一個都有一行。 我想遍歷數組,並為每個文件讀取其中的行並將其存儲在變量中。 我試過這個
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
兩個回聲都顯示空格。 如果我做
echo `basename $filename`
它確實顯示文件名。 上面的循環有什么問題?
基本問題是您似乎混合了 bash 和 tcsh 語法——碰巧您使用的 tcsh 命令恰好不是 bash 中的語法錯誤,但沒有做您想做的事。
這個:
set fl = `basename $filename`
是您如何將$fl
設置為 tcsh 中$filename
的基本名稱。 然而,在 bash 中, set
命令完全不同。 因為無論如何這不是你需要在這里使用的東西,所以我不會詳細介紹 go,但你可以在這里閱讀它們。
在 bash 中,設置變量的方式就是
var=value # NO spaces around the "="
此外,與 tcsh 不同,bash 有一個$(command)
語法來捕獲命令的 output,除了舊的`command`
。
所以你的命令
set fl = `basename $filename`
應該
fl="$("basename $filename")"
在$filename
引用和$(...)
命令替換周圍添加雙引號可確保 shell 可以處理文件名和/或命令 output 中的奇數字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.