Reputation: 23
I've got a ton of files as follows
audiofile_drums_1-ktpcwybsh5c.wav
soundsample_drums_2-fghlkjy57sa.wav
noise_snippet_guitar_5-mxjtgqta3o1.wav
louder_flute_9-mdlsiqpfj6c.wav
I want to remove everything between and including the "-" and the .wav file extension, to be left with
audiofile_drums_1.wav
soundsample_drums_2.wav
noise_snippet_guitar_5.wav
louder_flute_9.wav
I've tried to do delete everything following and including the character "-" using
rename 's/-.*//' *
Which gives me
audiofile_drums_1
soundsample_drums_2
noise_snippet_guitar_5
louder_flute_9
And for lack of finding an easy way to rename all the files again, adding .wav the extension, I am hoping there is a slicker way to do this in one nifty command in one stage instead of 2.
Any suggestions?
Thanks
Upvotes: 1
Views: 1060
Reputation: 23
This works in my specific case, but should work for any file extension.
rename -n 's/-.*(?=\.wav$)//' *
The command looks for all characters after and inclusive of the -
symbol in the filename, then, using a positive lookahead** (?=\.wav$)
to search for the characters (the file extension in this case) at the end of the filename (denoted by $
, and replaces them with no characters (removing them).
** NOTE: A positive look ahead is a zero width assertion. It will affect the match but it will not be included in the replacement. (The '.wav' part will not be erased)
In this example (?=\.wav$)
is the positive lookahead. The dollar sign $, as in regex, denotes at the end of the line, so perfect for a file extension.
Upvotes: 1
Reputation: 2016
You can use rename 's/-[^\.]*\.wav$/\.wav/' *
The first part -[^\.]*\.wav$
searchs for a - followed by n chars that are not .
followed by .wav
and the end of filename. The end of filename and .wav
is not strictly needed but it helps avoid renaming files you don't want to rename.
The /\.wav/
preserves the extension.
Please not that rename
is not a standard utility, and is part of perl, so rename
may not be available on every linux system.
Upvotes: 1