Reputation: 185
I need to rename PDF's in a folder. Someone keeps sending them to me with different filenames. However, the last 1 or 2 digits are good. They should be the same.
and so on. Only the last number should be kept,
I've tried to substitue the result from regex, but with no luck. The code works when i use something like sed 's/2017/foo/ '. But i need the pattern of the last number before .pdf in the result .. What's the error, what i'm doing wrong?
#!/bin/bash
find /home/foo/bar/ -type f -iname "NK*" -print0 | while read -d $'\0' f
do
mv "$f" "`echo $f | sed 's/.+\([0-9]{1,3}\.pdf\)/number\1/'`";
done
Upvotes: 2
Views: 95
Reputation: 22428
Change your mv
command to this:
mv "$f" "$(echo "$f" | sed 's/.*[^0-9]\([0-9]\{1,3\}\.pdf\)/number\1/')"
Basic regex does not support the following:
.+
(use .*
instead){m,n}
(use \{m,n\}
instead)Upvotes: 2
Reputation: 1439
The issues with your answer are you missed $
on your variable and you are escaping parenthesis you need in your regular expression.
#!/bin/bash
find /home/foo/bar/ -type f -iname "NK*" -print0 | while read -d $'\0' f
do
mv "$f" "`echo $f | sed 's/.* ([0-9]{1,3}).pdf/number$1.pdf/'`";
done
The un-escaped parenthesis allows you to access groups in variable form. First set is $1
and it increases from there by one.
Upvotes: 0