use awk to replace parentheses?
Solution 1
With sed:
echo -e "192.168.0.25,Up,()\n1.2.3.4,Up,(host.domain.com)" |
sed 's/()/None/g;s/[()]//g'
192.168.0.25,Up,None
1.2.3.4,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 "1.8.0.5,Up,()\n1.2.3.4,Up,(host.d.com)" | awk -f ip.awk
for example.
Solution 2
This should work -
awk -F"," -v OFS="," '
$NF=="()" {print $1,$2,"NONE";next}
{gsub(/\(|\)/,"",$NF);print}' INPUT_FILE
Explanation:
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.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 printNONE
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 simplefor loop
would be ideal. Just make sure thefor loop
works likei=1;i<NF;i++
this way you can manually put the final field. We also usenext
keyword to move to the next line since we don't want the second action to run on the first line.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.
Test:
[jaypal:~/Temp] cat file
192.168.0.24,Up,()
192.168.0.25,Up,(host.domain.com)
192.168.0.24,Up,()
192.168.0.24,Up,()
192.168.0.25,Up,(host.domain.com)
192.168.0.25,Up,(host.domain.com)
[jaypal:~/Temp] awk -F"," -v OFS="," '
$NF=="()" {print $1,$2,"NONE";next}
{gsub(/\(|\)/,"",$NF);print}' file
192.168.0.24,Up,NONE
192.168.0.25,Up,host.domain.com
192.168.0.24,Up,NONE
192.168.0.24,Up,NONE
192.168.0.25,Up,host.domain.com
192.168.0.25,Up,host.domain.com
Related videos on Youtube
LVLAaron
Updated on September 18, 2022Comments
-
LVLAaron over 1 year
How can I use awk to replace the parentheses in these 2 scenarios?
Change empty parens to the word "None"
192.168.0.24,Up,()
Remove parens to only host.domain.com is left
192.168.0.25,Up,(host.domain.com)
-
Admin over 12 yearsPlease 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.
-
enzotib over 12 yearsOr add a
#!/usr/bin/akw -f
shebang, make it executable and call it asecho -e "...." | ip.awk
-
Nikhil Mulley over 12 yearskamaal hain yaar Jaypal :-)