Renaming mutiple files with hyphens in name

I have searched throught a host of threads to figure out how to rename mutiple files at once using a script.

I need to convert 200+ files from:

fKITLS_120605-0002-00001-000001.hdr to eStroop_001.hdr
fKITLS_120605-0002-00002-000002.hdr to eStroop_002.hdr
and so forth....

What is throwing me off is the hyphens (-) in the name. Any help would be greatly appreciated.
Thanks

cd to the directory that holds the files

rm mvcmds.sh
for filename in `ls -1|grep ^fK`
do
NewStr="eStroop_"
OldStr=`echo $filename|awk -F"." '{print substr($1,length($1) -2, length($1))}'`
NewName=""$NewStr""$OldStr"".hdr""
echo "mv $filename $NewName" >> mvcmds.sh
done

If you like the mv commands that are generated in the file mvcmds.sh, run it.
Hope this helps

Assuming the dash-delimited field before the dot is always 6 characters wide:

for f in *.hdr; do
    mv "$f" eStroop_"${f##*-???}"
done

Regards,
Alister

Command works lovely.
Thanks again for the help.

That will work with the filenames given in this thread, but in general it's a very poor practice.

Any filename containing an IFS character (by default a space, tab, or newline) would be broken into pieces after the command substitution, with each piece served up individually to a different loop iteration.

The -1 flag to ls is pointless when piping to another process. ls knows when it's not writing to a tty and will always output one file per line (although if a filename itself contains a newline, it's not possible to know where it ends).

Since pathname expansion happens after field splitting (so that there's no need to worry about what the filename may contain) and since there's no need for multiple fork-execs to create the ls-grep pipeline, a safe and more efficient alternative to your approach would be:

for filename in fK*

Regards,
Alister

P.S. And, yes, I agree. Anyone using newlines and tabs in filenames deserves what they get. :wink:

1 Like

Thanks Alister .. dont know what started me off with that approach a long time ago .. but never too late to get over a bad habit ... Good info, Thanks!