Reputation: 408
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
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
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$ 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 stringUpvotes: 3
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