Home > Mobile >  How to get contents from 2 files and append that contents to a new file using a shell script
How to get contents from 2 files and append that contents to a new file using a shell script

Time:09-02

I have 2 files which look like this

file1.txt

GYFUFGYO1  KMP-app   [email protected]  CODE_SMELL
GYFUFGYO2  KMP-app   [email protected]  CODE_SMELL
GYFUFGYG3  AFP-Login   [email protected]  BUG
GYFUFGYG4  AFP-Login   [email protected]  BUG
GYFUFGYO5  KMP-app   [email protected]  CODE_SMELL
GYFUFGYO6  KMP-app   [email protected]  CODE_SMELL

file2.txt

MAC 135 2022-09-02-09:35

I have to append those contents(file1, file2) to file3.txt then expected output is

GYFUFGYO1  KMP-app   [email protected]  CODE_SMELL MAC 135 2022-09-02-09:35
GYFUFGYO2  KMP-app   [email protected]  CODE_SMELL MAC 135 2022-09-02-09:35
GYFUFGYG3  AFP-Login   [email protected]  BUG     MAC 135 2022-09-02-09:35
GYFUFGYG4  AFP-Login   [email protected]  BUG     MAC 135 2022-09-02-09:35
GYFUFGYO5  KMP-app   [email protected]  CODE_SMELL MAC 135 2022-09-02-09:35
GYFUFGYO6  KMP-app   [email protected]  CODE_SMELL MAC 135 2022-09-02-09:35

this is what I tried

paste -s file1.txt file2.txt > file3.txt

then output is (file3.txt)

GYFUFGYO1  KMP-app   [email protected]  CODE_SMELL   GYFUFGYO2  KMP-app   [email protected]  CODE_SMELL   GYFUFGYG3  AFP-Login   [email protected]  BUG       GYFUFGYG4  AFP-Login   [email protected]  BUG       GYFUFGYO5  KMP-app   [email protected]  CODE_SMELL   GYFUFGYO6  KMP-app   [email protected]  CODE_SMELL
BAU 133 2022-09-02-09:35

Can someone help me to figure out this? Thanks in advance!

CodePudding user response:

Assuming file2.txt has just one line as shown, how about a paste solution:

paste file1.txt <(yes $(<file2.txt) | head -n $(wc -l <file1.txt))
  • yes $(<file2.txt) repeats the line of file2.txt.
  • $(wc -l <file1.txt) returns the line count of file1.txt.
  • head -n $(wc -l <file1.txt) prints as many lines as file1.txt.

CodePudding user response:

paste expects two file of equal length. I'm guessing you basically want this common Awk two-liner:

awk 'BEGIN { FS=OFS="\t" } NR==FNR { a[  i] = $0; next }
    { print $0, a[(FNR-1) % i   1] }' file2.txt file1.txt

(I have assumed your files are tab-separated; it's not clear from your question.)

  • Related