0
votes

I need to print certain fixed values as well as values from other files, file1 and file2 into new file output using awk command.

file1:

100,1
102,3
104,4

file2:

103,4
108,6
109,7

my command

I did with the help of paste command: In file1:first 4 fields are present In file3:contents between file1 and file2 Merged all files using paste command. I wanted to do it directly without paste command usage awk -F '{print "100",0,1,contents_of_file1,"1","0",contents_of_file2}' > output

output:

100,0,1,100,1,1,0,103,4
100,0,1,102,3,1,0,108,6
100,0,1,104,4,1,0,109,7

First 3 values are default fixed, 4th and 5th column values are from file1,6th and 7th column values are fixed default values and last 2 columns are contents of file2

1
I need to do X is not a good question. You should explain what you want to do, what you've tried and where you're stuck. See How to Ask for more information.Tom Fenech
See the edit to see what I have trieduser3823859
It's better but it's not clear where all the fields in your output come from. You should edit to show us.Tom Fenech
edited output section aboveuser3823859

1 Answers

2
votes

It is possible to do the whole thing in one invocation of awk, by saving the contents of the first file to a buffer:

awk -v OFS=, 'NR==FNR{a[NR]=$0;next}{print "100,0,1",a[FNR],"1,0",$0}' file1 file2

The NR==FNR condition on the first block means that it is only run for the first file, where the total record number is equal to the record number for the current file. Each line from the first file is saved to the array a, using the record number as the index. next skips any further statements.

For the second file, the first block is skipped as NR is no longer equal to FNR. The value from the array corresponding to the same record in the first file is used, along with the fixed values and the contents of the current record, $0. Each field in the output is separated by OFS, which has been set to a comma.

Alternatively, you could use paste to feed in the content of both files at the same time:

paste -d, file1 file2 | awk -F, -v OFS=, '{print "100,0,1",$1,$2,"1,0",$3,$4}'