Concatenate rows in Linux file

2

I need to generate a linux script that concatenates information. I have a file (arch1.txt) that contains first and last names:

Juan Perez
Ana Lopez

and I have another script that, when executed, returns a line that contains the age of the people in the file arch1.txt. For example, the result for the two existing people is as follows:

1711089378 22 H
0976324852 25 M

I need to concatenate this data and that arch1.txt now contains this

Juan Perez 20
Ana Lopez 25

Thank you very much

    
asked by Kevtho 17.03.2017 в 05:48
source

2 answers

6
arch1.txt    arch2.txt
---------    ---------
Juan Perez   1711089378 22 H
Ana Lopez    0976324852 25 M

If you execute the following, it will show you the result you want

awk 'NR==FNR{a[NR]=$0;next}{print a[FNR],$2}' arch1.txt arch2.txt

Juan Perez 22
Ana Lopez 25

NR Give the total number of records processed

FNR Give the total number of records for each file

{a[NR]=$0;next} fills matrix a with records processed from file arch1.txt

next causes awk to stop processing the current file and move to the next file in this case arch2.txt

{print a[FNR],$2} prints the results adding the word or text found in the field $2 of the file arch2.txt which in this case is the age

Awk Built-in Variables

To save the result obtained in arch1.txt you can use a third file let's say output.txt to store these results and then move them to arch1.txt

awk 'NR==FNR{a[NR]=$0;next}{print a[FNR],$2}' arch1.txt arch2.txt > output.txt && mv output.txt arch1.txt

Then you can look at the content of arch1.txt and you will have the result you want

$ cat arch1.txt

Juan Perez 22
Ana Lopez 25
    
answered by 17.03.2017 в 07:46
2

Another alternative is the command join which by default "unites" the files based on the first column, so we use nl to pass each file with the lines numbered as the first column. For the output we say that we want field 2 and 3 of file 1 ( 1.2,1.3 ) and field 3 of file 2 ( 2.3 ).

join -o 1.2,1.3,2.3 <(nl arch1.txt) <(nl arch2.txt)
    
answered by 04.07.2017 в 03:42