How to write a script to rename files?

I have files 263_V01_C07_R000_THx_BH_4096H.dat,263_V01_C07_R000_THY_BH_4096H.dat and so on. I would like to change all R000 to R011. I tried like this:

#!/bin/bash

for file in *.dat; do
  if [[ "$file" =~ _THx_ ]]; then
mv $file $file2
  fi
done

But how to determine file2?

+4
source share
3 answers

You can replace characters in a variable like this

file2=${file/R000/R011}
+1
source

You can use rename:

rename R000 R011 *

There seem to be different versions around; the older one, which is part of the util-linux project , using the syntax above, and the newer one, Larry Wall, using the Perl expression to rename

rename 's/R000/R011/' *

Check your man page renameto see which one you have.

0

rename

rename 's/R000/R011/' *.dat
0

Source: https://habr.com/ru/post/1619913/


All Articles