Truncate all files in a directory after underscore?

0

I have a directory with a couple thousand images in it. Most of them have sensible filenames like SD-000.tif SD-001.tif BX-000.tif etc...

However probably ~25% of them have names like BX-003_old.tif BX-004_veryold.tif

How can I rename the problem files by removing the _word from the end of the each?

The files are stored on a FreeBSD server however the directory is shared out via samba.

I tried using combinations of sed and awk but I'm not having any luck getting them to only work with the middle of the files.

Does anyone have any ideas?

torcod

Posted 2011-08-10T21:17:15.473

Reputation: 11

Answers

1

newname=${filename%_*}.${filename##*.}

${filename%_*} gives the part before the last underscore.
${filename##*.} gives you the part after the last dot (the extension).

glenn jackman

Posted 2011-08-10T21:17:15.473

Reputation: 18 546

In case anyone ever ends up having a similar problem in the future I ended up fixing this with the cut command. – torcod – 2011-08-11T19:46:56.817

0

In case anyone ever ends up having a similar problem in the future I ended up fixing this with the cut command. I ran:

for i in *
do
mv $i `echo $i|cut -d"_" -f1`
done

The loop simply selects all files in the current directory and the cut -d specifies to truncate everything after the specified character. In my case the _.

torcod

Posted 2011-08-10T21:17:15.473

Reputation: 11

You don't care about the file's extension? – glenn jackman – 2011-08-11T20:22:56.600