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
0

1 Answer 1

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)
5
  • Can you explain your code please !!
    – unicorn
    Commented Nov 5, 2021 at 8:30
  • I added the explanation of the expansion. Anything else you find confusing?
    – choroba
    Commented Nov 5, 2021 at 8:32
  • What does ? do?
    – unicorn
    Commented Nov 5, 2021 at 9:10
  • @unicorn: It's a wildcard like * but it only matches a single character.
    – choroba
    Commented Nov 5, 2021 at 9:19
  • Thanks it worked !
    – unicorn
    Commented Nov 5, 2021 at 9:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .