Sachin Singh Sachin Singh - 1 year ago 69
Bash Question

Remove character occurring after _ from all the files excluding file extension (.png)

I was searching for a unix command/shell script to remove characters occurred after _ in all the files excluding file extension.



should be renamed to


I have tried searching online and but was not able to find out a quick and optimal solution.

Please note that those extra characters are added randomly and varying in each file.

Thanks in Advance!

Answer Source

You can use sed like this using a negated character class:

sed 's/_[^_.]*//' <<< "$f"


[^_.] matches any character except DOT or underscore.

If you're using bash then you can do this in shell itself using:

echo "${f%_*}.png"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download