3

I have multiple files with names for instance

ahard.txt
asoft.txt
bhard.txt
bsoft.txt
chard.txt
csoft.txt

I want to loop over these files, but process them in groups, so that Xhard.txt and aXsoft.txt are used as input files, and X.txt as output file, where the letter X stands for a, b, c etc. (it is actually a single letter in the filenames).

I have tried:

#!/bin/bash

i=$(ls *.txt)

for x in $i do pipeline nser=2 input1="${x/soft.txt}" input2="${x/hard.txt}" outfile="${x/hard.txt}" done

AdminBee
  • 22,803
unicorn
  • 33
  • 4

1 Answers1

7

You can use parameter expansion to extract the first character of a filename:

#! /bin/bash
for soft in ?soft.txt ; do
    letter=${soft:0:1}
    hard=${letter}hard.txt
    if [[ ! -f $hard ]] ; then
        echo "$hard not found" >&2
        continue
    fi
    echo "$soft $hard $letter.txt"
done
  • ${soft:0:1} returns the first character from $soft (position 0, length 1).

Note that it doesn't report an Xhard with a missing Xsoft.

BTW, using $(ls ...) is almost always wrong. Iterate over an expanded glob as in the snippet above, or populate an array directly without ls:

files=(*.txt)
choroba
  • 47,233