Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk command to merge the content of the same file

Tags:

bash

sed

awk

I have an input file with the following content

1 1
2 1
3 289
4 1
5 2 
0   Clear
1   Warning
2   Indeterminate
3   Minor
4   Major
5   Critical

I want to merge the first type of lines with the messages by the first column and obtain

  1 1 Warning
  2 1 Indeterminate
  3 289 Minor 
  4 1 Major
  5 2 Critical
like image 841
user_D_A__ Avatar asked Dec 20 '25 02:12

user_D_A__


2 Answers

Just use awk:

awk '$1 in a { print $1, a[$1], $2; next } { a[$1] = $2 }' file

Output:

1 1 Warning
2 1 Indeterminate
3 289 Minor
4 1 Major
5 2 Critical
like image 155
konsolebox Avatar answered Dec 23 '25 05:12

konsolebox


Using join/sed, sed creates different views of the file for each part and join joins on the common field:

join <(sed '/^[0-9]* [0-9]* *$/!d' input) <(sed '/^[0-9]* [0-9]* *$/d' input)

Gives:

1 1 Warning
2 1 Indeterminate
3 289 Minor
4 1 Major
5 2  Critical
like image 29
perreal Avatar answered Dec 23 '25 05:12

perreal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!