Search code examples
macosunixsedrenamefile-rename

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?


Solution

  • 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#*_*_}"