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.

  • 1
    Hi and welcome to U&L, please remember to mark the answer that solved your problem as accepted (the tick mark to the left of the answer). – terdon Aug 21 '13 at 22:33
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 
   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.

  • thank you very much!! you are awesome. You solved my problems and saved me from wasting lots of time on that. – AiB Aug 21 '13 at 22:21
  • 1
    No problem! Like the other question if you can mark it as the accepted answer that would be appreciated! – Drav Sloan Aug 21 '13 at 22:23
  • If you could mark it as so that would be great, details at meta.stackoverflow.com/help/someone-answers – Drav Sloan Aug 22 '13 at 9:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.