0

I have a file :

aaa
bbb
ccc

and another one:

111
222
333
444
.
.
999

My desired output after appending should be :

aaa 111
bbb 222 
ccc 333 
aaa 444
bbb 555
ccc 666
.
.
.
aaa nnn

I can append fixed strings with awk and sed, but I'm not able to figure out the looping over a fixed number of lines with different strings. While the second long file exists as a file, the strings to append don't have to be in a file, but since it is 11 lines of looping in the real case, I assume another file is the right ay to read them in.

3
  • Can we see the already-existing Source Lines of Code pertaining to the awk and sed Areas, @Rajib?
    – user1018743
    Commented Dec 8, 2019 at 11:05
  • sed 's/^/"string"/g' appends to the beginning of each line. But that is not relevant in this instance. Which is why I refrained from putting it in the question. @DOBRESCU_Mihai
    – Rajib
    Commented Dec 8, 2019 at 11:31
  • We understand that probably you want to write a nice Bourne-Again Shell-Script, @Rajib. Can you start by writing a small algorithm in Pseudo-Code that describes what you want to achieve? That action could intensively clarify your Issue for everyone else who might be interested in solving it.
    – user1018743
    Commented Dec 8, 2019 at 13:18

2 Answers 2

2

With sed, bash, a function and two global variables (counter and f1).

counter=1
getnext() {
  f1=$(sed -n "${counter}p" file1)
  if [[ "$f1" == "" ]]; then
    counter=1
    f1=$(sed -n "${counter}p" file1)
  fi
  ((counter++))
}

while read -r f2; do getnext; echo "$f1 $f2"; done <file2

Output:

aaa 111
bbb 222
ccc 333
aaa 444
bbb 555
ccc 666
aaa 777
bbb 888
ccc 999
3
  • Thanks. I'll try this out and let you know. Is file 1 the shorter "prepending" file?
    – Rajib
    Commented Dec 9, 2019 at 10:26
  • yes, file1 is the shorter one.
    – Cyrus
    Commented Dec 9, 2019 at 18:46
  • this worked perfectly.
    – Rajib
    Commented Dec 13, 2019 at 11:18
0

A solution with awk. The prepending file (that goes to the first column) is loaded to the array arr at BEGIN section. The - (stdin) can be replaced by the file name.

The second file is the normal awk input.

echo -e 'a\nb\nc'|
awk 'BEGIN {
        while ((getline < "-") > 0) {
                arr[i++] = $0
        }
}

{
        if (j in arr) {
                print arr[j++], $0
                next
        }
        j = 0
        print arr[j++], $0
}' <(echo {1..10}|tr ' ' '\n')

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .