-2

I have 2 files with some content/lines.

Example :

cat a.txt
  1
  2
  3
  4

cat b.txt
  a
  b
  c
  d

Need to get below output using for loop

 1 a
 2 b
 3 c
 4 d

I have tried the below script but it gives the wrong output

for i in `cat a.txt`
 do 
  for j in `cat b.txt`
   do 
     echo $i and $j
   done
 done

1 and a
1 and b
1 and c
1 and d
2 and a
2 and b
2 and c
2 and d
3 and a
3 and b
3 and c
3 and d
4 and a
4 and b
4 and c
4 and d

Kindly help me to do with For loop. Thanks in Advance

7
  • 2
    A for loop is not the right solution for this, is this a homework question?
    – jesse_b
    Jun 15 at 17:58
  • 3
    You have two nested loops, so of course you get all pairings. You'd need to read once from both files on each iteration. Or just use paste a.txt b.txt
    – ilkkachu
    Jun 15 at 18:01
  • 2
  • 1
    @Beginner In the comments, you mention that your data is different from what you show in the question. Could you please update the question with the actual data and expected result? If paste -d ' ' a.txt b.txt is "the wrong answer" for you, then please also explain why. There is absolutely no need for any for loop to solve this.
    – Kusalananda
    Jun 15 at 20:39
  • 1
    Are these the same two files you talk about in your other recent question? If so, the two files may be of different lengths, and you should mention this in the question and incorporate this fact in the test data and the expected output. I also still lack an explanation as to why the obvious solution with paste is not acceptable to you.
    – Kusalananda
    Jun 16 at 7:38

1 Answer 1

3

As @ilkkachu comments, paste is the best answer:

paste a.txt b.txt

or, with a single space as the delimiter in place of tab,

paste -d ' ' a.txt b.txt

For a shell-only answer, first don't read lines with for and Why is using a shell loop to process text considered bad practice?

You can use a single while loop to read lines from 2 files simultaneously

while IFS= read -r lineA <&3; IFS= read -r lineB <&4; do
    echo "$lineA $lineB"
done 3<a.txt 4<b.txt

if you like more whitespace for readability:

while IFS= read -r lineA <&3
      IFS= read -r lineB <&4
do
    echo "$lineA $lineB"
done 3<a.txt 4<b.txt

Another alternative: read each file into an array, then iterate over the array indices.

mapfile -t a < a.txt
mapfile -t b < b.txt
for idx in "${!a[@]}"; do printf '%s %s\n' "${a[idx]}" "${b[idx]}"; done
2
  • Can I get this done by for loop. Is it possible?
    – Beginner
    Jun 16 at 1:26
  • @Beginner I believe the last example in the answer is a for loop.
    – Kusalananda
    Jun 16 at 6:07

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.