Derek Edwards
Derek Edwards

Reputation: 113

How to remove characters in filename up to and including second underscore

I've been looking around for a while on this and can't seem to find a solution on how to use sed to do this. I have a file that is named:

FILE_772829345_D594_242_25kd_kljd.mov

that I want to be renamed

D594_242_25kd_kljd.mov

I currently have been trying to get sed to work for this but have only been able to remove the first second of the file:

echo 'FILE_772829345_D594_242_25kd_kljd.mov' | sed 's/[^_]*//'
_772829345_D594_242_25kd_kljd.mov

How would I get sed to do the same instruction again, up to the second underscore?

Upvotes: 0

Views: 1915

Answers (2)

Gordon Davisson
Gordon Davisson

Reputation: 125788

If the filename is in a shell variable, you don't even need to use sed, just use a shell expansion with # to trim through the second underscore:

filename="FILE_772829345_D594_242_25kd_kljd.mov"
echo "${filename#*_*_}"    # prints "D594_242_25kd_kljd.mov"

BTW, if you're going to use mv to rename the file, use its -i option to avoid file getting overwritten if there are any name conflicts:

mv -i "$filename" "${filename#*_*_}"

Upvotes: 3

codeforester
codeforester

Reputation: 42999

If all your files are named similarly, you can use cut which would be a lot simpler than sed with a regex:

cut -f3- -d_ <<< "FILE_772829345_D594_242_25kd_kljd.mov"

Output:

D594_242_25kd_kljd.mov

Upvotes: 1

Related Questions