MacUsers
MacUsers

Reputation: 2229

AWK: How to use OFS ignoring blank and commented out lines

I'm trying to rewrite a file on the fly, like this:

10.213.20.173, mem_chld, p3b-aggr-103, c3.xlarge, db, mysql
#10.213.20.191, mem_leaf, p3b-leaf-101, r3.xlarge, db, mysql
10.213.20.192, mem_leaf, p3b-leaf-102, r3.xlarge, db, mysql

10.213.20.190, mem_leaf, p3b-leaf-103, r3.xlarge, db, mysql
.....

from the original , separated filed to a : separated ones. So, I used this:

awk -F', ' 'BEGIN{OFS=":";} { $1=$1; print }'

which is pretty much working but that file also has some blank and commented out lines, which I also want to exclude. My attempt with:

awk -F', ' '!/^(#|$)/ {OFS=":";} { $1=$1; print }'

did not work as I expected. How can I do that? Best!

Upvotes: 1

Views: 242

Answers (3)

jaypal singh
jaypal singh

Reputation: 77105

Using awk:

$ awk -F', ' 'BEGIN{OFS=":"} !/^#/ && NF{$1=$1; print}' file
10.213.20.173:mem_chld:p3b-aggr-103:c3.xlarge:db:mysql
10.213.20.192:mem_leaf:p3b-leaf-102:r3.xlarge:db:mysql
10.213.20.190:mem_leaf:p3b-leaf-103:r3.xlarge:db:mysql

alternatively you can set OFS like:

awk -F', ' -v OFS=':' '!/^#/ && NF{$1=$1; print}' file

or even

awk -F', ' '!/^#/ && NF{$1=$1; print}' OFS=':' file

As Ed Morton suggested in the comments, for an edge case where you might have space before the # it is best to use the following:

awk -F', ' 'BEGIN{OFS=":"} !/^[[:space:]]*#/ && NF{$1=$1; print}' file

Explanation:

$1=$1 rebuilds the $0 variable. It takes all the fields and concatenates them, separated by OFS which we have set to : instead of space which is the default.

Upvotes: 5

konsolebox
konsolebox

Reputation: 75488

awk -F', ' -v OFS=: '/^[ \t]*(#|$)/{next}{$1=$1}1' file

Output:

10.213.20.173:mem_chld:p3b-aggr-103:c3.xlarge:db:mysql
10.213.20.192:mem_leaf:p3b-leaf-102:r3.xlarge:db:mysql
10.213.20.190:mem_leaf:p3b-leaf-103:r3.xlarge:db:mysql

Upvotes: 0

Sylvain Leroux
Sylvain Leroux

Reputation: 52000

What about:

awk -F', ' -v OFS=':' '/^[^#]/ {$1=$1; print}' datafile

This will ignore both empty lines and lines starting with a # sign.

If comments might be preceded by some spaces, you would prefer:

awk -F', ' -v OFS=':' '!/^[ \t]*(#.*)?$/ {$1=$1; print}' datafile

Upvotes: 2

Related Questions