1

I am beginner in shell script . I have one variable containing value having = character. I want to add quote in fields after = Character.

abc="source=TDG"
echo $abc|awk -F"=" '{print $2}'

My code is printing one field only. my expected output is

source='TDG'
Cœur
  • 37,241
  • 25
  • 195
  • 267
user2916639
  • 388
  • 1
  • 3
  • 18

3 Answers3

3
$ abc='source=TDG'
$ echo "$abc" | sed 's/[^=]*$/\x27&\x27/'
source='TDG'
  • [^=]*$ match non = characters at end of line
  • \x27&\x27 add single quotes around the matched text


With awk

$ echo "$abc" | awk -F= '{print $1 FS "\047" $2 "\047"}'
source='TDG'
  • -F= input field separator is =
  • print $1 FS "\047" $2 "\047" print first field, followed by input field separator, followed by single quotes then second field and another single quotes
  • See how to escape single quote in awk inside printf for more ways of handling single quotes in print


With bash parameter expansion

$ echo "${abc%=*}='${abc#*=}'"
source='TDG'
  • ${abc%=*} will delete last occurrence of = and zero or more characters after it
  • ${abc#*=} will delete zero or more characters and first = from start of string
Sundeep
  • 23,246
  • 2
  • 28
  • 103
  • Swap your use of quotes in sed so you can avoid those ugly hex codes: `" ' ' "` – Harvey Feb 16 '17 at 13:41
  • 1
    @Harvey while it would work in this case, one needs to be careful using double quotes as it will be interpreted by shell before getting passed to sed – Sundeep Feb 16 '17 at 13:44
3

Sed would be the better choice:

echo "$abc" | sed "s/[^=]*$/'&'/"

Awk can do it but needs extra bits:

echo "$abc" | awk -F= 'gsub(/(^|$)/,"\047",$2)' OFS==
grail
  • 914
  • 6
  • 14
0
What is taking place?

Using sub to surround TDG with single quotes by its octal nr to avoid quoting problems.

echo "$abc" | awk '{sub(/TDG/,"\047TDG\047")}1'
source='TDG'
Claes Wikner
  • 1,457
  • 1
  • 9
  • 8
  • 1
    While this code may answer the question, providing additional context regarding why and/or how it answers the question would significantly improve its long-term value. Please [edit] your answer to add some explanation. – CodeMouse92 Feb 16 '17 at 18:28