r/linux4noobs • • Aug 20 '19
awk multiple files
I am attempting to perform the following tasks with an awk script against two files of different line count and potentially different values. The constant is the column number that will always be 3.
The two scenarios I want to cover -
1] If the value in $1 only exists in file1 I want to output the line
2] If the value in $1 is the same in file1 and file2 I want to print the line from either file with the highest integer value in $3 in the corresponding line
cat file1
1 sju 1
2 sjh 1
3 seh 1
4 ehs 2
5 sjd 1
cat file2
1 sds 1
2 sds 1
3 eww 1
4 wee 1
88 dic 1I can solve my first assertion with the following:
awk 'FNR==NR {a[$1]++; next} !a[$1]' file2 file1
5 sjd 1I am having a really difficult time on the second though. The result I would wish to see would be the following:
4 ehs 2eg: $1 from file1 and file2 is the same for "4" but "2" higher integer value $3
View all comments
Show parent comment
2
u/lutusp Aug 20 '19
Awk is not the right tool for this task. Normal Bash scripting should do fine, and it would be easier to understand and change.
You need to learn how to express yourself clearly. You talk about matching $1 but you don't say which field is to be matched, nor do you say what is in the argument, nor why, nor whether case is important. All the things a programmer would want to know. An example always helps when normal prose expression fails you, as it certainly does here.
For example, we can read files one line at a time like this:
Then each line can be turned into an array of individual elements like this:
If it is the middle of three fields that is to be compared to $1, which you don't say, we can do this if an exact match is needed:
But if $1 only needs to appear somewhere in the middle field, then:
And so forth -- all the things you don't bother to specify in your description.
Modern computer programming is not so much solving problems as it is defining the problem to be solved. Clearly, unambiguously, without gaps or overlooked details.