Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add ' before every line using awk?

Tags:

bash

awk

Using this command, I can add " before every line.

awk '{print "\""$0}' file

But I want to add ' instead of ", why this command doesn't work?

awk '{print "\'"$0}' file
like image 323
Yishu Fang Avatar asked Nov 30 '22 21:11

Yishu Fang


1 Answers

You absolutely CANNOT use a single quote inside a single-quote-delimited script as that quote absolutely denotes the end of that script [segment]. The options you have are:

  1. Put the script in a file "foo" as {print "'"$0} and execute as: awk -f foo file, or
  2. Use the escape sequence \047 everywhere you want to print a quote: awk '{print "\047"$0}' file, or
  3. Save the quote in a variable: awk -v q=\' '{print q$0}' file, or
  4. Delimit the awk script with double instead of single quotes and escape anything the shell might care about: awk "{print \"'\"\$0}" file
  5. Drop out of awk and back to shell just to get the quote: awk '{print "'\''"$0}' file

The final list item above is actually 2 separate segments of awk script ('{print "' and '"$0}') with a bit of shell in the middle (\') so when the end result is of concatenating those is passed by shell to the awk command for execution, you get what you want.

FWIW I'd use "1" if your script is more than a couple of lines, "2" or "3" otherwise with "3" being my personal preference but YMMV. I wouldn't do 4 or 5.

like image 138
Ed Morton Avatar answered Dec 04 '22 05:12

Ed Morton