2

I have many files with the same prefix and the same suffix. I want to remove both from filenames. Both contain spaces.

So foo bar XXX doo par.jpg, foo bar YY YY doo par.jpg would become XXX.jpg and YY YY.jpg

4

With prename:

Setup:

$ mkdir test && cd test
$ > "foo bar XXX doo par.jpg"; > "foo bar YY YY doo par.jpg"

Action:

$ rename -n 's/^foo bar //; s/ doo par(\.[^.]*)$/$1/'  *
  foo bar XXX doo par.jpg renamed as XXX.jpg
  foo bar YY YY doo par.jpg renamed as YY YY.jpg

(Remove the -n to have those moves actually performed)

  • @BinaryZebra prename should stand for perl rename. There are others, or so I hear. – PSkocik Feb 8 '16 at 23:45
  • Sorry, @PSkocik my bad. – user79743 Feb 9 '16 at 1:41
  • Thank you - worked like a charm! The comment from BinaryZebra was way too much over my head, but yours are way simplier. – John Taylor Feb 9 '16 at 8:31
  • @BinaryZebra No problem. I usually do make a lot of typos, so I do appreciate edits. – PSkocik Feb 9 '16 at 8:52
3

If the filename is in a variable, the canonical way to remove a preffix is:

removepre="foo bar "
filename="foo bar XXX doo par.jpg"
filename="${filename#"$removepre"}"
echo "$filename"

The problem with the suffix you present is that there is an extension that you want to preserve, so it becomes a bit longer:

removesuf=" doo par"
filename="foo bar XXX doo par.jpg"
extension="${filename##*.}"            ### store extension in a variable.
filename="${filename%.*}"              ### remove extension.
filename="${filename%"$removesuf"}"    ### remove suffix.
filename="$filename.$extension"        ### re-place the extension
echo "$filename"

All joined in one script:

#!/bin/bash
filename="$1"

removepre="foo bar "
filename="${filename#"$removepre"}"

removesuf=" doo par"
extension="${filename##*.}"            ### store extension in a variable.
filename="${filename%.*}"              ### remove extension.
filename="${filename%"$removesuf"}"    ### remove suffix.
filename="$filename.$extension"        ### re-place the extension
echo "$filename"

Call the script as this:

$ ./script "foo bar XXX doo par.jpg"
XXX.jpg"

Understand that quotes are a must to process file names with spaces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.