Bash如何在两个目录中执行文件命令

问题描述 投票:0回答:2

我知道这个bash代码用于对一个目录中的所有文件执行操作:

for files in dir/*.ext; do 
cmd option "${files%.*}.ext" out "${files%.*}.newext"; done

但是现在我必须对一个目录中的所有文件执行一个操作,其中所有文件都在另一个目录中,文件名相同但扩展名不同。例如

directory 1 -> file1.txt, file2.txt, file3.txt
directory 2 -> file1.csv, file2.csv, file3.csv

cmd file1.txt file1.csv > file1.newext
cmd file2.txt file2.csv > file2.newext

我不能比较两个文件,但我必须执行的脚本需要两个文件来生成另一个文件(特别是我必须执行bwa samsa path_to_ref/ref file1.txt file1.csv > file1.newext

你可以帮帮我吗?

谢谢您的回答!

linux bash
2个回答
1
投票

在使用变量操作的bash中:

$ for f in test/* ; do t="${f##*/}";  echo "$f" test2/"${t%.txt}".csv ; done
test/file1.txt test2/file1.csv
test/file2.txt test2/file2.csv
test/file3.txt test2/file3.csv

编辑:

实施@DavidC.Rankin的保险建议:

$ touch test/futile
for f in test/*
do 
  t="${f##*/}"
  t="test2/${t%.txt}".csv
  if [ -e "$t" ]
  then 
    echo "$f" "$t"
  fi
done
test/file1.txt test2/file1.csv
test/file2.txt test2/file2.csv
test/file3.txt test2/file3.csv

0
投票

试试:

for file in path_to_txt/*.txt; do 
   b=$(basename $file .txt)
   cmd path_to_txt/$b.txt path_to_csv/$b.csv 
done
  • 如果此命令不需要,则不要包含调用“cmd”的路径。
  • “for”语句如果在.txt文件的目录中运行,则不能包含该路径
  • 如果执行时间是必需的,则可以用posix regexp替换basename。看到这里https://stackoverflow.com/a/2664746/4886927
© www.soinside.com 2019 - 2024. All rights reserved.