Remove characters preceding the second underscore in file names

bashcommand lineterminalunix

I have a bunch of files and I would like to remove all characters preceding the second underscore in the file names. An example is shown below. How do I do this using bash commands?

[From]

021_D05_53715-F.ab1
021_D06_53936-F.ab1
022_C06_53935-F.ab1
030_C08_53993-F.ab1
048_A12_54057-F.ab1

[To]

53715-F.ab1
53936-F.ab1
53935-F.ab1
53993-F.ab1
54057-F.ab1

Best Answer

Bash can figure out where the last underscore is using a regular expression match, then you can use its substring extraction to get the part of the filename that you care about. Something like this:

#!/bin/bash

file="021_D05_53715-F.ab1"
pos=`expr "$file" : '^.*_'`
newfile=${file:$pos}
echo "$file -> $newfile"