简体   繁体   中英

Bash How to execute a command for files in two directories

I know this bash code for execute an operation for all files in one directory:

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

But now I have to execute an operation for all files in one directory with all files in another directory with the same filename but different extension. For example

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

I must not to compare two files, but the script that I have to execute needs two file to produce another one (in particular I have to execute bwa samsa path_to_ref/ref file1.txt file1.csv > file1.newext )

Could you help me?

Thank you for your answers!

In bash using variable manipulation:

$ 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

Edit:

Implementing @DavidC.Rankin's insuring suggestion:

$ 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

Try with:

for file in path_to_txt/*.txt; do 
   b=$(basename $file .txt)
   cmd path_to_txt/$b.txt path_to_csv/$b.csv 
done
  • do not include the paths in call to "cmd" if this command doesn't need them.
  • "for" statement can not include the path if it is run at directory of .txt files
  • if execution time is a requisite, you can replace basename by posix regexp. See here https://stackoverflow.com/a/2664746/4886927

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM