1

I have infile with values for 2 variables

# cat infile
A 1
B 2
C
D
E

I want to read variable a & b, so that if $b has null value, it should repeat like 1..2, till all $a values are read.

so if I use a loop that does echo $a $b

# cat loop.sh
#!/usr/bin/env bash

cat infile | while read a b do echo $a $b done

result is somewhat same as infile.

But I want an if statement that should repeat $b, so that it should echo

A 1
B 2
C 1
D 2
E 1
Sollosa
  • 1,929
  • 4
  • 20
  • 38
  • It is not quite clear, could you add more details on how the output is arrived at? or more examples? – Inian Aug 27 '21 at 06:19

1 Answers1

1

Assuming that once the second column runs out of values, there will be no further values in that column,

awk '{ if ($2 == "") $2 = saved[(i++)%n]; else saved[n++] = $2 }; 1' file

This reads the values of the second column into the saved array with index 0 holding the first value and incrementing n each time. When the second column runs out of values, this array is used to populate the column in a cyclic fashion, using i as a counter and folding its value back to zero at multiples of n using the modulus operator.

Testing:

$ cat file
A 1
B 2
C
D
E
$ awk '{ if ($2 == "") $2 = saved[(i++)%n]; else saved[n++] = $2 }; 1' file
A 1
B 2
C 1
D 2
E 1
$ cat otherfile
A apple
B bumblebee
C sunshine
D
E
F
G
H
$ awk '{ if ($2 == "") $2 = saved[(i++)%n]; else saved[n++] = $2 }; 1' otherfile
A apple
B bumblebee
C sunshine
D apple
E bumblebee
F sunshine
G apple
H bumblebee
Kusalananda
  • 333,661