user2916639
user2916639

Reputation: 408

Field separation with adding quotes

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'

Upvotes: 1

Views: 144

Answers (3)

Claes Wikner
Claes Wikner

Reputation: 1517

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'

Upvotes: 0

Sundeep
Sundeep

Reputation: 23667

$ 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

Upvotes: 3

grail
grail

Reputation: 930

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==

Upvotes: 3

Related Questions