Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape {} in awk?

Tags:

linux

bash

awk

I have many of the input lines as seen below, where I would like to end up with an output similar to this

host tsclient010.tsclient {
   option host-name "tsclient010.tsclient";
   hardware ethernet 00E0C56BF96D;
   fixed-address 192.168.246.10;
}

fore ach of the inputs. However I run into the problem that the static content contains {}.

echo "192.168.246.10 00E0C56BF96D tsclient010.tsclient" | awk '{print
host $3 {
   option host-name "$3";
   hardware ethernet $2;
   fixed-address $1;
}
}'

Output:

awk: cmd. line:2:     host $3 {
awk: cmd. line:2:             ^ syntax error

I have tried to escape it by '\{', but doesn't work.

Question

Does anyone know how to escape the needed chars?

like image 444
Sandra Schlichting Avatar asked Oct 18 '25 06:10

Sandra Schlichting


2 Answers

You don't need to escape the braces. You need to quote them and escape the double quotes.

awk '{printf "\
host %s {\
   option host-name \"%s\";\
   hardware ethernet %s;\
   fixed-address %s;\
}\n", $3, $3, $2, $1
}'
like image 142
William Pursell Avatar answered Oct 19 '25 21:10

William Pursell


  1. Text inside double quotes is text. Text not inside double quotes is awk script.
  2. The newline delimeters awk commands.

You can:

echo "192.168.246.10 00E0C56BF96D tsclient010.tsclient" | awk '{
    print "host "$3" {"
    print "option host-name \""$3"\";"
    print "hardware ethernet "$2";"
    print "fixed-address "$1";"
    print "}"
}'

or

echo "192.168.246.10 00E0C56BF96D tsclient010.tsclient" | awk '{
    print "host "$3" {\noption host-name \""$3"\";\nhardware ethernet "$2";\nfixed-address "$1";\n}" }'
like image 21
KamilCuk Avatar answered Oct 19 '25 22:10

KamilCuk



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!