1

I have files with this format: ddmmyyyyRANDOM.mp3

and i want to rename them in: yyyy-mm-dd-RANDOM.mp3

RANDOM is a random string which can include spaces. not a homework question. I am struck here and i tried various regex but coudnt find out. I need to write bash script

2
  • Take a look at unix.stackexchange.com/q/161987/74329 Commented Oct 14, 2014 at 9:39
  • have a look at the perl rename utility that has all the beautiful power of perl-regexps! Commented Oct 14, 2014 at 9:56

4 Answers 4

2

I would break in parts by method of substring

 filename="ddmmyyyyRANDOM.mp3"
part1=${filename:0:8} #this should get you ddmmyyy
part2=${filename:9:6} #this should get you RANDOM
filenamenew=$part1$part2".mp3"
mv $fileneme $filenamenew

RUN in a loop if you have more than 1 filename

Sign up to request clarification or add additional context in comments.

3 Comments

RANDOM is well, a random not non-fixed-length string to subscripting doesn't work here
Well if you get the length of the string at start then its possible
Random part would be total length - 8 - 4 (-4 because .mp3 is 4 letters)
0

Try this:

FILE="23022014hello world.mp3"
mv "$FILE" "$(echo "$FILE" | sed 's/\([0-9]\{2\}\)\([0-9]\{2\}\)\([0-9]\{4\}\)\(.*\)/\3-\2-\1-\4/')"

It cuts the first 2 numbers, second 2 numbers, next 4 numbers and remaining characters separately and arranges according to your requirement.

Comments

0

try this:

for file in *; do
    new=$(echo "$file" | sed -r 's/^([0-9]{2})([0-9]{2})([0-9]{4})(.*)$/\3-\2-\1-\4/')
    mv "$file" "$new" 
done

more about regex HERE

Comments

0

Use the rename utility

touch 12021960RANDOM.mp3 "01041973 random with spaces.mp3"

$ rename -n 's/^(\d{2})(\d{2})(\d{4})/$3-$2-$1-/' *.mp3
01041973 random with spaces.mp3 renamed as 1973-04-01- random with spaces.mp3
12021960RANDOM.mp3 renamed as 1960-02-12-RANDOM.mp3

When you're happy with the output, remove the -n part to actually perform the rename

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.