Bash-change for for循环中的目录

时间:2018-02-22 17:10:54

标签: bash for-loop

当你进行for循环时,如何更改输出中的目录?

示例:

for f in ./test/Sample1_out/*coords
do
    ./test/sort.pl --in1 "$f" --in2  "./test/Sample1_out/count.txt" --out "${f/.coords/.sorted}"
done
  1. 如果我想向上移动目录以将文件保存在" ./ test /"目录,我该怎么做?

  2. 如果我想循环遍历所有Sample文件夹,我该怎么办呢? (我尝试了for f in ./test/*out/*coords; do ./test/sort.pl --in1 "$f" --in2 "./test/*out/count.txt" --out "${f/.coords/.sorted},但我的--in2被清空了)

1 个答案:

答案 0 :(得分:0)

要处理多个目录,我只想添加另一个循环:

for dir in ./test/*_out/; do
    for file in "$dir"/*.coords; do
        ./test/sort.pl --in1 "$file" --in2 "$dir/count.txt" \
                       --out "${file/.coords/.sorted}"
    done
done

或者您可以同时在两个级别上使用glob,并使用dirname${file%/*}获取当前文件所在目录的名称:

for file in ./test/*_out/*.coords; do
    ./test/sort.pl --in1 "$file" --in2 "${file%/*}/count.txt" \
                   --out "${file/.coords/.sorted}"
done

--in2 "./test/*out/count.txt"不起作用,通配符不会在引号中展开,你会得到一个带有文字星号的路径。)

至于输出文件,我不确定你想要什么,但是如果你想要其他目录中的所有输出文件,那么就像这样:

outfile=${file##*/}       # remove directory part of path (or use basename)
                          # stick new path in, and change extension
outfile=/path/to/output/${outfile/.coords/.sorted}  
./test/sort.pl --in1 "$file" --in2  "$dir/count.txt" \
               --out "$outfile"

或者如果您想要“上一个目录”,可以使用"${file%/*/*}/${file##*/}"/foo/bar/abc.txt转换为/foo/abc.txt