0

So I have two text files

  • FILE1: 1-40 names
  • FILE2: 1-40 names

Now what I want the program to do (Terminal) is to go through each name, by incrementing by ONE in each file so that the first name from FILE1 runs the first line from FILE2, and 20th name from FILE1 runs the 20th line from FILE2.

BUT I DON'T WANT IT TO run first name of FILE1, and then run through all of the names listed in FILE2, and repeat that over and over again. Should I do a for loop?

I was thinking of doing something like:

for f in (cat FILE1); do 
    flirt -in $f -ref (cat FILE2); 
done

I'm doing this using BASH.

codeforester
  • 39,467
  • 16
  • 112
  • 140
hsayya
  • 131
  • 1
  • 10

3 Answers3

4

Yes, you can do it quite easily, but it will require reading from two-different file descriptors at once. You can simply redirect one of the files into the next available file descriptor and use it to feed your read loop, e.g.

while read f1var && read -u 3 f2var; do
    echo "f1var: $f1var -- f2var: $f2var"
done <file1.txt 3<file2.txt

Which will read line-by-line from each file reading a line from file1.txt on the standard file descriptor into f1var and from file2.txt on fd3 into f2var.

A short example might help:

Example Input Files

$ cat f1.txt
a
b
c

$ cat f2.txt
d
e
f

Example Use

$ while read f1var && read -u 3 f2var; do \
echo "f1var: $f1var -- f2var: $f2var"; \
done <f1.txt 3<f2.txt
f1var: a -- f2var: d
f1var: b -- f2var: e
f1var: c -- f2var: f

Using paste as an alternative

The paste utility also provides a simple alternative for combining files line-by-line, e.g.:

$ paste f1.txt f2.txt
a       d
b       e
c       f
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
0

In Bash, you might make usage of arrays:

echo "Alice
> Bob
> Claire" > file-1

echo "Anton
Bärbel
Charlie" > file-2

n1=($(cat file-1))
n2=($(cat file-2))

for n in {0..2}; do echo ${n1[$n]} ${n2[$n]} ; done

Alice Anton
Bob Bärbel
Claire Charlie
user unknown
  • 35,537
  • 11
  • 75
  • 121
0

Getting familiar with join and nl (number lines) can't be wrong, so here is a different approach:

nl -w 1 file-1 > file1
nl -w 1 file-2 > file2 
join -1 1 -2 1 file1 file2 | sed -r 's/^[0-9]+ //'

nl with put a big amount of blanks in front of the small line numbers, if we don't tell it to -w 1.

We join the files by matching line number and remove the line number afterwards with sed.

Paste is of course much more elegant. Didn't know about this.

user unknown
  • 35,537
  • 11
  • 75
  • 121