2

I have a pdf files in the format:

Author-YYYY-rest_of_text_seperated_by_underscores.pdf
John-2010-some_file.pdf
Smith-2009-some_other_file.pdf

I need to rename the files so that the year is first e.g.

YYYY-Author-rest_of_text_seperated_by_underscores.pdf
2010-John-some_file.pdf
2009-Smith-some_other_file.pdf

So that would mean moving the 'YYYY-' element to the start.

I do not have unix 'Rename' and must rely on sed, awk etc.I happy to rename inplace.

I have been trying to adapt this answer not having much luck. Using sed to mass rename files

Community
  • 1
  • 1
BenP
  • 825
  • 1
  • 10
  • 30
  • 1
    Please don't tag questions with tools that aren't actually at the center of the question itself. `awk` and `sed` may be useful in an answer, but they're not what you're actually asking about. – Charles Duffy Mar 07 '17 at 17:10

2 Answers2

5

See BashFAQ #100 for general advice on string manipulation with bash. One of the techniques this goes into is parameter expansion, which is heavily used in the below:

pat=-[0-9][0-9][0-9][0-9]-
for f in *$pat*; do  # expansion not quoted here to expand the glob
  prefix=${f%%$pat*} # strip first instance of the pattern and everything after -> prefix
  suffix=${f#*$pat}  # strip first instance and everything before -> suffix 
  year=${f#"$prefix"}; year=${year%"$suffix"} # find the matched year itself
  mv -- "$f" "${year}-${prefix}-${suffix}"    # ...and move.
done

By the way, BashFAQ #30 discusses lots of rename mechanisms, among them one using sed to run arbitrary transforms.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
3

Using BASH regex:

re='^([^-]+-)([0-9]{4}-)(.*)$'

for f in *.pdf; do
    [[ $f =~ $re ]] &&
    echo mv "$f" "${BASH_REMATCH[2]}${BASH_REMATCH[1]}${BASH_REMATCH[3]}"
done

When you're happy with the output remove echo command before mv.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • recieved an error 'conditional binary operator expected' – BenP Mar 07 '17 at 17:18
  • I've tested it in BASH and it worked without any error. Make sure you are using `bash` as well – anubhava Mar 07 '17 at 17:19
  • 2
    @BenP, hmm -- this *should* work. What's your shebang? If you were running your script with `/bin/sh` instead of bash, that would be expected to cause a failure. – Charles Duffy Mar 07 '17 at 17:19