0

I've seen many examples here on how to replace filenames using strings within the filename (for example, myfile_000121.txt changed to 000121.txt). But what if I have a separate text file where I saved all my filenames in the first column and a completely new ID in the second column? The ID is not found anywhere within the original filenames.

Here is an example of my textfile:

AA5t-666_S241_L002_R1_001.fastq.gz  Species_uno_R1.fastq.gz
AA5t-666_S241_L002_R2_001.fastq.gz  Species_uno_R2.fastq.gz
AA5t-662-0788-AES_L002_R1_001.fastq.gz  Species_duo_R1.fastq.gz
AA5t-662-0788-AES_L002_R2_001.fastq.gz  Species_duo_R2.fastq.gz

So I want to use this textfile to replace the filenames in my directory (the same names in column 1) with the new names I created in column 2. I'm only aware of how to do something like this if the ID name appears within the filename.

Thank you!

  • Read each column into different variables, then just use those variables as arguments to the `mv` command. – Barmar Feb 10 '23 at 16:02
  • Would it just be something like, for line in filelist.txt; do col1=(extract col1 somehow); col2=(extract col2 somehow); mv col1 col2; done. I just need to figure out how to save the columns as variables. – Katherine Chau Feb 10 '23 at 16:03
  • You don't know how to read a file line by line in a shell script? – Barmar Feb 10 '23 at 16:04
  • Sometimes but I often just run into issues with using the while read command - I tend to stick to for loops. – Katherine Chau Feb 10 '23 at 16:06
  • 1
    See https://stackoverflow.com/questions/1521462/looping-through-the-content-of-a-file-in-bash/1521498#1521498 – Barmar Feb 10 '23 at 16:07

1 Answers1

1

Read each column of the file into a variable and then use them as arguments to the mv command.

while read -r oldname newname
do
    mv "$oldname" "$newname"
done < filelist.txt
Barmar
  • 741,623
  • 53
  • 500
  • 612