Remove pattern from filenames Remove pattern from filenames unix unix

Remove pattern from filenames


The simplest method is to use the common rename command which is available in most Unices.

rename 's/^mywork_myfile_/mywork_/' *

This of course expects you to be on the directory of the files. This will not overwrite files. If you want that, just pass the -f option. Also, take note that there's multiple versions of rename out there which may have different options.


Based on this answer on "Rename all files in "Rename all files in directory from $filename_h to $filename_half?", this can be a way:

for file in mywork_myfile*txtdo   mv "$file" "${file/_myfile/}"done

Note that it uses the bash string operations as follows:

$ file="mywork_myfile_XSOP.txt"$ echo ${file/_myfile/}mywork_XSOP.txt


This would work in any Posix shell...

#!/bin/shfor i  in mywork_myfile_XSOP.txt \     mywork_myfile_ATTY.txt \     mywork_myfile_ATPY.txt; do       set -x       mv "$i" "$(echo $i | sed -e s/myfile_//)"       set +xdone