-2

I have a list of strings in String that I want to add at the beginning of all files names of Targets in the folder. All files are ordered.

String.txt:

ID1Somestring_
IDISomeOtherString_
IDISomeThirdString_

Targets:

example1.fastq
example2.fastq
example3.fastq

output:

ID1Somestring_example1.fastq
IDISomeOtherString_example2.fastq
IDISomeThirdString_example3.fastq
user2300940
  • 2,355
  • 1
  • 22
  • 35

1 Answers1

1

First, read the file into an array

mapfile -t strings < String.txt

Then, iterate over the files and access each array element in turn:

n=0; for file in *fastq; do echo mv "$file" "${strings[n++]}$file"; done
mv example1.fastq ID1Somestring_example1.fastq
mv example2.fastq IDISomeOtherString_example2.fastq
mv example3.fastq IDISomeThirdString_example3.fastq

Or, assuming your filenames do not contain newlines

paste String.txt <(printf "%s\n" *fastq) |
while read -r string file; do echo mv "$file" "$string$file"; done
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • That paste+while also assumes they don''t contain any white space. You could add `IFS=$'\t'` before the `read` and then it'd just rely on the first arg not containing any tabs which is a bit better (I personally come across file names with blanks every day but rarely if ever tabs or newlines). – Ed Morton Oct 24 '18 at 12:21
  • spaces in the filename are not a problem. The first whitespace-separated field goes into "string" and the rest of the line goes into "file". – glenn jackman Oct 24 '18 at 13:27
  • 1
    I was referring to the file name prefixes stored in String.txt containing spaces, that's what I mean by `the first arg` but I wasn't clear. – Ed Morton Oct 24 '18 at 14:02