11

how can I remove the word "myfile" in a list of filenames with this structure?

mywork_myfile_XSOP.txt
mywork_myfile_ATTY.txt
mywork_myfile_ATPY.txt

Desired_output:

mywork_XSOP.txt
mywork_ATTY.txt
mywork_ATPY.txt    
fedorqui
  • 275,237
  • 103
  • 548
  • 598
Fuv8
  • 885
  • 3
  • 11
  • 21

3 Answers3

11

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.

carandraug
  • 12,938
  • 1
  • 26
  • 38
5

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*txt
do
   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
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • Well, this *is* the cleanest way. Although it is bash-specific and won't work in other shells, not even other Posix-style ones, that's probably OK these days. Everyone ships bash. – DigitalRoss Dec 18 '13 at 17:26
  • The question is tagged `bash`, so I wouldn't worry about POSIX compatibility. That said, in general, one cannot assume that `bash` is the system shell (Ubuntu) or that the system shell is a current version of `bash` (Mac OS X). – chepner Dec 18 '13 at 17:29
  • Well, good points, tho actually the question is *not* tagged bash. – DigitalRoss Dec 18 '13 at 17:30
  • It was when I commented. – chepner Dec 18 '13 at 17:31
  • My fault, I edited the question and added the `bash` as per the kind of question. Removing it. – fedorqui Dec 18 '13 at 17:31
3

This would work in any Posix shell...

#!/bin/sh

for 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 +x
done
alper
  • 2,919
  • 9
  • 53
  • 102
DigitalRoss
  • 143,651
  • 25
  • 248
  • 329