0

I was wondering whether it is possible to reuse whatever was matched in a path with globbing? (Just as it can usually be done with regex substitutions?)

I'm aware that there are other solutions for the following example, but I'm just using it as an example for what I'm asking: Let's say have the files file_1.txt, file_2.txt, ..., file_100.txt in the current folder, and I'd like to rename them to asdf_1_qwer.txt, asdf_2_qwer.txt, ..., asdf_100_qwer.txt. Of course I could match them with file_*.txt, but can I somehow reuse whatever was matched in * for specifiying the target file name?

muru
  • 72,889
flawr
  • 135
  • 4
  • 1
    Can you show how you would want to do it? No, there is no equivalent to regex capture groups in the shell, but you can get close by saving things in variables. What would you want to save here? – terdon Sep 20 '23 at 08:02
  • I would use Perl's rename: rename -n 's/.*(\d+).*/asdf_${1}_qwer.txt/' ./file_[0-9]*.txt – Gilles Quénot Sep 20 '23 at 13:07

1 Answers1

1

While there is no direct equivalent to regex capture groups in the shell, what you describe is usually done using variables. For example:

$ for f in file_*.txt; do
   number="${f/file_/}" 
   number="${number/.txt/}" 
   printf 'The number from file "%s" is "%d"\n' "$f" "$number"
done
The number from file "file_1.txt" is "1"
The number from file "file_2.txt" is "2"
The number from file "file_3.txt" is "3"

Or, using sed instead of shell string manipulation:

$ for f in file_*.txt; do    
    number=$(sed -E 's/^file_([0-9]+)\.txt/\1/' <<<"$f"); 
    printf 'The number from file "%s" is "%d"\n' "$f" "$number"; 
done
The number from file "file_1.txt" is "1"
The number from file "file_2.txt" is "2"
The number from file "file_3.txt" is "3"
terdon
  • 242,166