Renaming files based on the contents of a text file

filesrename

I have lots of point files I need to change for model input. I want to rename lots of these files based on the contents of a file. These files are text files arranged in rows.

file name: data_lat_long.txt

1 data_20_20
2 data_30_40
3 data_50_60
.
.

and so on

my files are named 1, 2, 3, 4, etc,.

I want 1 to be changed in to data_20_20, 2 in to data_30_40 and so on.

Best Answer

while read line ; do 
    mv $line 
done < data_lat_long.txt

Redirect the contents of data_lat_long.txt to a while loop that uses read to read in the each line of the file and for each line assign it to a variable called $line. Then run mv with the contents of $line as an argument (which is the from and to parts you have specified in your data_lat_long.txt file). Keep on looping until the end of file.

Note this implicitly expects that neither file names in your data_lat_long.txt contain spaces (so that there are only two columns).

If files have spaces in them, then I suggest a comma separator in your file:

1,space file1
2,space file2
3,space file3

and then use:

while IFS=',' read -a files 
do 
   mv "${files[0]}" "${files[1]}" 
done < list.txt

That makes use of the -a option of read which assigns the text separated by the IFS (in this case comma) to an array called $files. We then index the various elements on the mv and quote the arguments with double quotes "". This is so the array value is expanded on execution of the mv command and so the space in the file is not seen as argument separator by mv. mv 1 space file1 does not do the same thing as mv "1" "space file1". The former command attempts to move files/directories called 1 and space to a directory called file1.

Related Question