0

Given the following input

line1
line2
line3

would it be possible to append them all into a single array element and then output them the as

line1
line2
line3

with a single print statement? Semi-pseudo-code: awk '{[append $0 to a[test]}; END {print a[test]}' file1

A more complicated but more practical example problem is given two files, file 1 is:

line1
line2
line3

and file2 is:

linea
lineb
linec

how would I produce output like so:

linea
line1
line2
line3
lineb
line1
line2
line3
linec
line1
line2
line3

My assumption that this would require an array is what is underlining my original question.

A couple of tests such as a[test]+=$0 and a[test]=a[test]+$0 have predictably failed.

2
  • yes, possible. show a complete example pls. Commented Aug 2, 2017 at 14:24
  • Let me know if you require more expansion. Commented Aug 2, 2017 at 14:35

2 Answers 2

2

Like this:

$ awk '{
    a[1]=a[1] (a[1]==""?"":ORS) $1  # "append them all into a single array element"
} 
END {
    print a[1]                      # "output them - - with a single print statement"
}' file
line1
line2
line3

And for the latter part:

$ awk '
NR==FNR{
    a[NR]=$1; next
}
{
    b[FNR]=$1
}
END {
    for(i=1;i<=length(a);i++) {
        print a[i]
        for(j=1;j<=length(b);j++)
            print b[j]
    }
}
' file2 file1
linea
line1
line2
line3
lineb
line1
line2
line3
linec
line1
line2
line3
Sign up to request clarification or add additional context in comments.

1 Comment

your codes are very clear. however, you applied the worst time&space complexity Time: O(m*n), Space: O(m+n) one of a[NR] , b[FNR] hashtable is not necessary, since awk processes input line by line. You don't have to save data in memory and loop thru them later.
1

This does what you want:

awk 'NR==FNR{a=$0;next}{print;printf "%s", a}'  RS="\0" f1 RS="\n" f2

Test:

kent$  head f1 f2
==> f1 <==
line1
line2
line3

==> f2 <==
linea
lineb
linec

kent$  awk 'NR==FNR{a=$0;next}{print;printf "%s", a}'  RS="\0" f1 RS="\n" f2
linea
line1
line2
line3
lineb
line1
line2
line3
linec
line1
line2
line3

1 Comment

.. a bit of explaining or even pretty-printing for those starting to learn awk would be even more helpful : )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.