1

I have a directory under which I have 4 files

ERR315336_1.fastq.gz  ERR315336_2.fastq.gz  ERR315337_1.fastq.gz  ERR315337_2.fastq.gz

Also I have the info file for these 4 files in a sep file named info.txt

placenta_6c      placenta_6c_ERR315336_1.fastq.gz    ERR315336_1.fastq.gz
placenta_6c      placenta_6c_ERR315336_2.fastq.gz    ERR315336_2.fastq.gz
thyroid_5b   thyroid_5b_ERR315337_1.fastq.gz     ERR315337_1.fastq.gz
thyroid_5b   thyroid_5b_ERR315337_2.fastq.gz     ERR315337_2.fastq.gz

I want to change the name of my files in the directory from the info.txt file so after changing names my directory should look like this:

 placenta_6c_ERR315336_1.fastq.gz 
 placenta_6c_ERR315336_2.fastq.gz 
 thyroid_5b_ERR315337_1.fastq.gz 
 thyroid_5b_ERR315337_2.fastq.gz

So basically changing ERR315336_1.fastq.gz to placenta_6c_ERR315336_1.fastq.gz and so on. I have a huge info list file. How can I do this.

Thanks

user3138373
  • 2,559

2 Answers2

2

awk-ishly:

cd directory-with-files
awk '{system("echo mv " $3 " " $2)}' < /path/to/info.txt

bash-edly:

cd directory-with-files
while read -r junk new old
do
  echo mv "$old" "$new"
done < /path/to/info.txt

Remove the echo's when it looks good.

This does not do any error-checking for spaces in the filenames, or quote-marks in the filenames.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
2
$ while read -r c1 c2 c3; do echo mv "$c3" "$c2"; done < info.txt
mv ERR315336_1.fastq.gz placenta_6c_ERR315336_1.fastq.gz
mv ERR315336_2.fastq.gz placenta_6c_ERR315336_2.fastq.gz
mv ERR315337_1.fastq.gz thyroid_5b_ERR315337_1.fastq.gz
mv ERR315337_2.fastq.gz thyroid_5b_ERR315337_2.fastq.gz
  • Read the info.txt file line by line and save the 3 fields (assumes space/tab separation)
  • echo is for dry run, remove once it is okay
  • Further reading: http://mywiki.wooledge.org/BashFAQ/001
Sundeep
  • 12,008
  • One query: Why using quotes around $c3 and $c2?? I was stuck at this step and I didn't use quotes and it was giving me so destination operand error – user3138373 May 16 '17 at 16:45
  • using quotes avoids possible mangling of filenames due to shell interpretation.. see https://unix.stackexchange.com/questions/131766/why-does-my-shell-script-choke-on-whitespace-or-other-special-characters/131767#131767 but for given sample it shouldn't matter – Sundeep May 17 '17 at 00:21