1

I want to edit a bunch of files with a bash script. First I need the single path to the file as well as a counter. So far I came up with this:

let n=0
array=(`pwd`"/worker/worker*/conf/logfilefilter-worker*.xml")
for i in "${array[@]}"; do
  let "c += 1"
  echo $i
  echo $c
  # here comes the edit stuff.
done

But this loop just runs once:

[mles@sagnix etl-i_test]$ ./iprog_new --test
/home/devel/mles/etl-i_test/worker/worker01/conf/logfilefilter-worker01.xml     /home/devel/mles/etl-i_test/worker/worker02/conf/logfilefilter-worker02.xml /home/devel/mles/etl-i_test/worker/worker03/conf/logfilefilter-worker03.xml /home/devel/mles/etl-i_test/worker/worker04/conf/logfilefilter-worker04.xml /home/devel/mles/etl-i_test/worker/worker05/conf/logfilefilter-worker05.xml /home/devel/mles/etl-i_test/worker/worker06/conf/logfilefilter-worker06.xml /home/devel/mles/etl-i_test/worker/worker07/conf/logfilefilter-worker07.xml /home/devel/mles/etl-i_test/worker/worker08/conf/logfilefilter-worker08.xml
1

How will the loop run one by one trough the files?

4

1 回答 1

5

这个

array=(`pwd`"/worker/worker*/conf/logfilefilter-worker*.xml")

只是一个元素,因为文件名通配符 (for *) 在引用的字符串中被抑制。然后在"${array[@]}"单个元素中得到 glob 扩展,但由于双引号保持为单个字符串,所有文件名由空格分隔。做

array=(`pwd`/worker/worker*/conf/logfilefilter-worker*.xml)

或者

for i in ${array[@]}; do  # no double quotes

工作更好?另一方面,没有像数组这样的 bashim 的更便携的解决方案呢?迭代文件的规范方法是

for file in $PWD/worker/worker*/conf/logfilefilter-worker*.xml; do
   echo "$file"
done
于 2013-05-23T10:18:12.750 回答