I have the following variable
var="text1 value1.text value2"
I want to add specific characters at the start and the end of every word in variable
Τhe desired result I want it to be the following
[text1] [value1.text] [value2]
As far I can only add text only in all variable content
echo [$var]
output
[text1 value1.text value2]
Can you help me how to do it
preferably with awk
CodePudding user response:
You may use this awk:
awk '{for (i=1; i<=NF; i) $i = "[" $i "]"} 1' <<< "$var"
[text1] [value1.text] [value2]
Or a gnu-awk solution without looping:
awk -v RS='[[:space:]]' '{$0 = "[" $0 "]"; ORS=RT} 1' <<< "$var"
[text1] [value1.text] [value2]
CodePudding user response:
printf "[%s] " "$var"
Disadvantage: There is one trailing space in output.
CodePudding user response:
set -f
var="text1 value1.text value2"
printf -v var "[%s] " $var
echo "${var% }"
Output:
[text1] [value1.text] [value2]
CodePudding user response:
It's not clear if you want to change the value of var or just output the contents of var with the square brackets added so take your pick:
$ var='text1 value1.text value2'
$ echo "[${var// /] [}]"
[text1] [value1.text] [value2]
$ var="[${var// /] [}]"
$ echo "$var"
[text1] [value1.text] [value2]
