0

I know how to extract a string by removing a prefix or suffix, but I don't know how to do both. Concretely, in the example below, how can I display inside my for-loop the names without a_ and _b?

$ touch a_cat_b a_dog_b a_food_b

$ for i in * ; do echo $i without a_ is ${i##a_} ;done;
a_cat_b without a_ is cat_b
a_dog_b without a_ is dog_b
a_food_b without a_ is food_b

$ for i in * ; do echo $i without _b is ${i%_b} ;done;
a_cat_b without _b is a_cat
a_dog_b without _b is a_dog
a_food_b without _b is a_food
Lolo
  • 3,935
  • 5
  • 40
  • 50
  • I think you would need a regex for that https://stackoverflow.com/questions/35919103/how-do-i-use-a-regex-in-a-shell-script what if your string has an internal `_` ? – KeepCalmAndCarryOn Dec 07 '22 at 09:30

2 Answers2

2

You can use the =~ operator:

#!/bin/bash

for f in *; do
    if [[ $f =~ ^a_(.*)_b$ ]]; then
        echo "$f without leading a_ and trailing _b is ${BASH_REMATCH[1]}"
    fi
done
M. Nejat Aydin
  • 9,597
  • 1
  • 7
  • 17
1

Use parameter expansion to select just the middle of the string?

for i in a_cat_b a_dog_b a_food_b; do
    printf "%s minux prefix and suffix is: %s\n" "$i" "${i:2:-2}"
done

${i:2-2} is the substring starting with the third (0-based indexes) character of $i, stopping at 2 before the end of the string.

This does assume the text you want to strip is fixed-length, of course.

Shawn
  • 47,241
  • 3
  • 26
  • 60
  • Thank you. Knowing how to access part of the string via index is useful but I prefer the other more generic solution – Lolo Dec 07 '22 at 10:24