Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I use awk to replace the parentheses in these 2 scenarios?

  1. Change empty parens to the word "None",Up,()

  2. Remove parens to only host.domain.com is left,Up,(host.domain.com)

share|improve this question
Please accept an answer if it helped resolve your question. If you have open issues, do leave a comment so that we can update the answer. – jaypal singh Jan 6 '12 at 8:25

With sed:

echo -e ",Up,()\n1.2.3.4,Up,(host.domain.com)" | 
    sed 's/()/None/g;s/[()]//g',Up,None,Up,host.domain.com

Here is an awk-program:

BEGIN {FS=","}
$3 ~ /\(\)/   { printf ($1","$2",None\n"); next }
$3 ~ /\(.+\)/ { 
                  gsub ("\\(", "")
                  gsub ("\\)", "")
              { printf ($0"\n") }

call it with

echo -e ",Up,()\n1.2.3.4,Up,(host.d.com)" | awk -f ip.awk 

for example.

share|improve this answer
Or add a #!/usr/bin/akw -f shebang, make it executable and call it as echo -e "...." | ip.awk – enzotib Jan 4 '12 at 7:20

This should work -

awk -F"," -v OFS="," '
$NF=="()" {print $1,$2,"NONE";next}
{gsub(/\(|\)/,"",$NF);print}' INPUT_FILE


  1. We set the Field Separator to , and Output Field Separator to ,. Setting OFS gives us the liberty to avoid printing your desired field separators explicitly.

  2. We check for a pattern $NF=="()" (where $NF is the last field), if it is true we print out the first and the second field and print NONE as the last field. Since your sample data only had three fields this approach should be ok. However, if you have more than 5 fields then using a simple for loop would be ideal. Just make sure the for loop works like i=1;i<NF;i++ this way you can manually put the final field. We also use next keyword to move to the next line since we don't want the second action to run on the first line.

  3. The second action statement is true for all the lines that don't match the first. Here we are using a global substitution built-in function which substitutes the brackets to nothing.

Hope this helps!


[jaypal:~/Temp] cat file,Up,(),Up,(host.domain.com),Up,(),Up,(),Up,(host.domain.com),Up,(host.domain.com)

[jaypal:~/Temp] awk -F"," -v OFS="," '
$NF=="()" {print $1,$2,"NONE";next}
{gsub(/\(|\)/,"",$NF);print}' file,Up,NONE,Up,host.domain.com,Up,NONE,Up,NONE,Up,host.domain.com,Up,host.domain.com
share|improve this answer
kamaal hain yaar Jaypal :-) – Nikhil Mulley Jan 4 '12 at 19:29
Thanks Nikhil. :) – jaypal singh Jan 4 '12 at 19:31

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.