Search code examples
bashfile-rename

Bash: Find specific files and cut last 5 characters from name


I have some files under my ./ folder, for example:

$ ls
XX
AArse
BArse
CCCAArse
YY
....

After some command I want:

AA
BA
CCCAA

I.e. If the end of the filename contains rse, the file gets renamed (to remove rse from it's name).

How do I implement some command in bash?


Solution

  • With bash:

    shopt -s nullglob
    for file in *rse; do
      mv -i "$file" "${file%rse}"
    done
    

    The shell option nullglob expands a non-matching glob pattern to a null string and the parameter expansion ${file%rse} removes the shortest suffix rse from the filename.

    Option -i prompts to overwrite already existing files.