I have two files with log output. I need to join them the way I described below

First file

Line 1
Line 2
Line 3

Second File

Need to be placed at the end of Line 1
Need to be placed at the end of Line 2
Need to be placed at the end of Line 3

Expected result:

Line 1 Need to be placed at the end of Line 1
Line 2 Need to be placed at the end of Line 2
Line 3 Need to be placed at the end of Line 3

I know how append text/input file using sed but in case of file it will insert all contents of a file so it's not what I am looking for. Any help appreciated:)

  • Does this answer your question? Print two files in two columns May 18 '21 at 17:32
  • @αғsнιη Doesn't seem to be an exact dupe as the user in the other question is aware of paste but tries to overcome a limitation in it.
    – Kusalananda
    May 18 '21 at 17:35
  • what if your inputs would looks like the ones mentioned in this answer? unix.stackexchange.com/a/392658/72456. do you mind lines of each files interference within each other position? May 18 '21 at 17:47
  • @Kusalananda emm, does the opinion of the asker there matter? May 18 '21 at 17:50

Assuming the files should be "joined together" line by line, use paste.

The paste utility takes input from one or several files, and produces output consisting of the files "pasted side by side". The paste utility creates columns of the files listed on its command line.

paste first_file second_file

To use a space as the delimiter between the files (instead of the default tab character), use paste with its -d option:

paste -d ' ' first_file second_file

See also the manual for paste on your system.

In a sense, paste does the opposite of cut, which extracts fields/columns.


Using awk:

awk 'NR==FNR { arr[NR]=$0; next}{ printf "%s %s\n", arr[FNR], $0 }' first_file second_file

NR==FNR{ arr[NR]=$0 This will create an array arr indexed on lines(record numbers) for first file only. This is because FNR is set to zero when awk starts reading second file whereas NR is total records read so far from all files, i.e. NR is not set to zero when new file is started for reading.

The next statement tells awk to stop processing current record(read line) and go to next record. This means no further commands will be executed for current line. Therefore, after creating array arr, the printf statement is not executed for first file.

Next printf prints arr and all records from second file.

I did nothing but slightly changed command taken from this answer.

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.