Home > Software engineering >  Batch rename file with regex: remove prefix
Batch rename file with regex: remove prefix

Time:08-19

I have files <uuid>_CS_Filename, and i want replace uuid_ => with ".*?_" to "".

How can I do this?

So, for;

1557acc7f3cd5d1538b71fe77bcf9ec0_My_filename_ch101.pdf

I want:

My_filename_ch101.pdf

I don't want to install some 3rd party packages; I searched the internet and only found brew install rename.

CodePudding user response:

Use sed:

filename="1557acc7f3cd5d1538b71fe77bcf9ec0_My_filename_ch101.pdf"
newname=$(echo $filename | sed -e 's/^[a-z0-9]*_//g')
# newname is "My_filename_ch101.pdf"

Assume the files to rename are all in current directory:

for f in $(ls); do
  mv $f $(echo $f | sed -e 's/^[a-z0-9]*_//g')
done

CodePudding user response:

Using cut:

cut -d '_' -f 2- <<<"1557acc7f3cd5d1538b71fe77bcf9ec0_My_filename_ch101.pdf"

Sample usage:

$ touch 1557acc7f3cd5d1538b71fe77bcf9ec0_My_filename_ch101.pdf
$ fname="1557acc7f3cd5d1538b71fe77bcf9ec0_My_filename_ch101.pdf"
$ ls $fname
1557acc7f3cd5d1538b71fe77bcf9ec0_My_filename_ch101.pdf
$ mv "$fname" $(cut -d '_' -f 2- <<<"$fname")
$ ls *My*
My_filename_ch101.pdf

CodePudding user response:

Using bash parameter expansions:

#!/bin/bash
for f in * ; do
  [[ -e "${f}" ]] || continue
  mv "${f}" "${f#*_}"
done
  • Related