Home concatenation of lines as a variable while comparing two files using awk
Reply: 0

concatenation of lines as a variable while comparing two files using awk

Maulik Upadhyay
1#
Maulik Upadhyay Published in 2018-01-11 16:47:59Z

I am comparing two files using awk. Following is representation of first file (file1.txt):

1
15
MRUKLM
GHLKGM
BNUIOK

Following is representation of second file (file2.txt):

AGHLKMT
MFBGSJY
GSBDGLM

I want to compare two files based on certain patterns. Moreover, first line of the output file should contain the total number of lines in the second file followed by second and third line of the first file. Hence, the header of the output file should be as follows:

3(total lines of second file)
15(second line of first file)
MRUKLM(third line of first file)
certain pattern.....
certain pattern....
certain pattern....

I wrote the following codes:

vari=$(wc -l file2.txt)|awk -v lin="" 'NR==FNR{if(NR>1 && NR<4)lin=$lin$0;else a[NR]=$0;next}BEGIN{print vari,lin}match($0,/([0-9]*)_(.*)/,c){print a[2*c[1]+2];print a[2*c[1]+3]}' file1.txt file2.txt> output_file.txt

The part of the code that extract the pattern is working perfectly, however, I could not get any header in the output file. The output I get is as follows:

certain pattern....
certain pattern....

It turns out that I did some mistakes in assigning variables. Following are the updated codes:

awk -v vari="$(cat file2.txt|wc -l)" 'NR==FNR{if(NR>1 && NR<4)print $0;else a[NR]=$0;next}BEGIN{print vari}match($0,/([0-9]*)_(.*)/,c){print a[2*c[1]+2];print a[2*c[1]+3]}' file1.txt file2.txt > output.txt

It is giving the desirable output.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.333937 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO