Reputation: 307
Below is the sample file where I would like to print values in the columns next to the match..
$> cat sample.txt
DATABASE ORACLE, DB_TYPE Relational, OS OEL 5
VERSION 12.2.0.1
DATABASE MongoDB, DB_TYPE NOSQL, OS RedHat 7
VERSION 3.2
DATABASE MySQL, DB_TYPE Relational
VERSION 5.5
The lines starting with DATABASE and VERSION I joined them as following:
$> grep -i "^DATABASE\|^VERSION" sample.txt | sed 'N;s/,/\t/;s/\n/\t/'
DATABASE ORACLE DB_TYPE Relational, OS OEL 5 VERSION 12.2.0.1
DATABASE MongoDB DB_TYPE NOSQL, OS RedHat 7 VERSION 3.2
DATABASE MySQL DB_TYPE Relational VERSION 5.5
But now I would like to print only the columns next to DATABASE, DB_TYPE and VERSION and I did some thing like this.
$> grep -i "^DATABASE\|^VERSION" sample.txt | sed 'N;s/,/\t/;s/\n/\t/' |awk -v val1='DATABASE' -v val2='DB_TYPE' -v val3='VERSION' -F ' ' '{for (i=1; i<=NF; i++) if ($i==val1 || $i==val2 || $i==val3) {n=i+1; print $n} }'
ORACLE
Relational,
12.2.0.1
MongoDB
NOSQL,
3.2
MySQL
Relational
5.5
But I am expecting some thing like this
ORACLE Relational 12.2.0.1
MongoDB NOSQL 3.2
MySQL Relational 5.5
Upvotes: 0
Views: 151
Reputation: 67497
awk
to the rescue!
$ tr ',' '\n' <file |
awk '/DATABASE|DB_TYPE|VERSION/{printf "%s",$2 OFS; if(++c%3==0)print""}'
ORACLE Relational 12.2.0.1
MongoDB NOSQL 3.2
MySQL Relational 5.5
you can set OFS to tab or pipe to column -t
for tabular formatting.
Upvotes: 2
Reputation: 2389
For your example, this will work:
grep -i "^DATABASE\|^VERSION" sample.txt | sed 'N;s/,/\t/;s/\n/\t/' | awk 'BEGIN { OFS = " " } /DATABASE/ {print $2,$4,$NF}'
Searches for occurrences of DATABASE, output file separator (OFS) is tab - figure out how to insert a tab between the quotes for your particular OS
Upvotes: 0