0

I have a bunch of files and these files come with pair. For example:

File1_1.tar.gz, File1_2.tar.gz
File2_1.tar.gz, File2_2.tar.gz
...

I take first pair and execute bunch of commands and get output, then I proceed to second pair. But I can only do this if the folder have two files like File1_1.tar.gz, File1_2.tar.gz after that I delete these and add second pair by hand. I take filenames from directory like this

FILE_1=$(ls | sort -n | head -n 1)
FILE_2=$(ls | sort -n | tail -n 1)

I would like do it with for loop like take the first two pair get output then take second pair get output and so on.

oguz ismail
  • 1
  • 16
  • 47
  • 69
Saruman
  • 61
  • 1
  • 8

1 Answers1

3

Here's what you know: each filename has two parts, separated by _. The first part is arbitrary, the second part is either 1.tar.gz or 2.tar.gz, and the files come in pairs.

This means you can simply iterate over one set, and use parameter expansion to generate the (known) other half of the pair.

for f1 in *_1.tar.gz; do
    base=${f1%_1.tar.gz}  # Strip _1.tar.gz, leaving File1, File2, etc
    f2=${f1%_1.tar.gz}_2.tar.gz  # add _2.tar.gz to get File1_2.tar.gz, etc
    ...
done
chepner
  • 497,756
  • 71
  • 530
  • 681