Sachin Singh Sachin Singh - 4 months ago 11
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.

Example:

b6d28-insurance-renewal-shop_6b5c74fa3d4b96f7557c3fd66f2555af.png

should be renamed to

b6d28-insurance-renewal-shop.png

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

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

f='b6d28-insurance-renewal-shop_6b5c74fa3d4b96f7557c3fd66f2555af.png'
sed 's/_[^_.]*//' <<< "$f"

b6d28-insurance-renewal-shop.png

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

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

echo "${f%_*}.png"