oezlem
oezlem

Reputation: 247

add special characters in a text using awk

I have a file which is :

line1
line2
line3

What I am trying to have is

"line1"{
"line1"
 }

I am trying to do this using awk but I don't know how to use the special characters. For now I have this.

awk '{ "$0" {"$0"} }' 

Upvotes: 2

Views: 1799

Answers (4)

Ed Morton
Ed Morton

Reputation: 204381

$ awk '{$0="\""$0"\""; print $0 "{\n" $0 "\n}"}' file
"line1"{
"line1"
}
"line2"{
"line2"
}
"line3"{
"line3"
}

Upvotes: 5

karakfa
karakfa

Reputation: 67547

as a comparison with sed

$ sed 's/.*/"&"{\n"&"\n}/' file

"line1"{
"line1"
}
"line2"{
"line2"
}
"line3"{
"line3"
}

also another awk

$ awk -v OFS="\n" -v q='"' '{v=q $0 q; print v "{", v, "}" }' file

Upvotes: 2

Kent
Kent

Reputation: 195229

You can simply use printf:

awk -v fmt='"%s"{\n"%s"\n}\n' '{printf fmt, $0,$0 }' file

Test with your data:

kent$  awk -v fmt='"%s"{\n"%s"\n}\n' '{printf fmt, $0,$0 }' f
"line1"{
"line1"
}
"line2"{
"line2"
}
"line3"{
"line3"
}

Upvotes: 1

Sundeep
Sundeep

Reputation: 23687

$ awk -v q='"' '{ql = q $0 q; print ql "{" ORS ql ORS "}" }' ip.txt
"line1"{
"line1"
}
"line2"{
"line2"
}
"line3"{
"line3"
}
  • -v q='"' save the double quote character in variable named q, makes it easier to insert double quotes instead of messing with escapes
  • ql = q $0 q this adds double quotes around the input record
  • ql "{" ORS ql ORS "}" required output, ORS is output record separator which is newline character by default
    • space between the different parameters is ignored, use " }" to get a space before } in the output

Upvotes: 3

Related Questions