简体   繁体   中英

Bash - file n of $1?

I've done a few things with bash lately, mainly about audio files (sox batch scripts). I try to learn, I'm reading and reading and searching, but sometimes "simple" questions I have to address just lead me to some tons of lines, web pages, and eventually no answer. This is one of them :

I need to address file 1 of a given input folder ( $1 ) , and compare one of its parameters to file 1 of another given input folder ( $2 ). By: "file 1", I mean : the first file that would be listed if you call the directory content; like :

for f in "$1"/*
do
  echo $f
done

My goal is to compare, by pair, file n of folder $1 with file n of folder $2 , where "n" is the "position" of the file in the folder, doesn't matter if they're listed by name or whatever, as they will be listed the same way in folder $1 and folder $2 when I run the script.

Applescript lets me address file 4 of folder 1 in a simple way; would it be much complicated in a bash script, or I am totally missing a basic thing ?

Thanks very much in advance

Surprisingly, this actually has a chance of working properly, since POSIX guarantees that the result of filename expansion is sorted according to the current locale (2.13.3 behind the link) and bash has to follow it. Note that different locales may yield different sorting orders, though.

Since the question is tagged "bash," I'll not bother with POSIX-conformity beyond that and suggest the use of bash arrays:

files=("$1"/*)
echo "${files[4]}"

This can also be used with a variable as index:

files=("$1"/*)
i=4
echo "${files[i]}"

I cannot, however, see how this construct could sanely be used, and it kind of sounds as though you're actually looking for diff -r "$1" "$2" or so.

When the filenames are equal (what is suggested by your responde to the answer of @Wintermute), you can handle it without arrays:

ls $1 | while read fileWithPath; do
   file=${fileWithPath##*/}
   echo "My own soxdiff between $1/$file and $2/$file"
done

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