Rename files

Hi,

I am new to Unix and i have a requirement where i need to write a shell script where i have to loop through various files present in a directory and rename them based on below criteria.

Files in the folder are in the following format. [S*\_V[0-9]_YYYYMMDD.dat]

SDL_V1_20100530.dat
SDP_V0_20100530.dat

etc.

we need to remove date part from the file names and final result should be the one like below.

SDL_V1.dat
SDP_V0.dat

Can you please help me in achieving that.

Thanks

Assuming you are in that folder and it only contains files which should be renamed, you could try something like following directly from the shell.
Of course you could write this in your shell script, in this case be sure that you have a proper shebang in the first line, eg #!/bin/sh

for i in *.dat; do
j=$(echo $i | sed 's/_[0-9]\{8\}//')
mv $i $j
done

I strongly recommend to copy your original files in a temporary directory, before you run the for loop from above, just for the case that you are not satisfied with it's output.
The sed command simply cuts an underline followed by 9 digits.

I checked that link and I wonder how that approach in concrete terms would look like :confused:

another way (checking for 2 underlines to avoid renaming renamed files)

for F in *_*_*.dat
do mv -v $F ${F%_*}.dat
done

There is no need to worry about renamed files in the for list; the sh expands the glob to generate the list before the loop body begins to execute. Still, a nice, simple, efficient solution, using parameter expansion to generate the new name.

Regards,
Alister

It was just in case of calling the script twice (what happened to me while testing :D)

Ah. heheh. Apologies for my misunderstandig. :wink: