Here are two other ways to do what you seem to want; one with sed
and one just using shell built-ins. (Note that in this suggested code the string assigned to var
starts with a <tab> followed by a <space> and ends with a <space> followed by a <tab> and all of the spaces and tabs are preserved in the output):
#!/bin/ksh
var=' Name 1,Value 1,"Name 2",Value 2,Name 3 , Value 3 '
printf '%s\n' "$var"|sed 's/\([^,]*,[^,]*\),/\1|/g'
( IFS=","
set -- $var
while [ $# -gt 2 ]
do printf '%s,%s|' "$1" "$2"
shift 2
done
[ $# -eq 0 ] && echo ''
[ $# -eq 1 ] && printf '%s\n' "$1"
[ $# -eq 2 ] && printf '%s,%s\n' "$1" "$2"
)
The above script produces the output:
Name 1,Value 1|"Name 2",Value 2|Name 3 , Value 3
Name 1,Value 1|"Name 2",Value 2|Name 3 , Value 3
(unfortunately, the CODE tags seem to be stripping off the trailing <space> and <tab> characters on the last line). So too verify that the spaces and tabs were preserved, when that script's output is piped through od -bc
, the output is:
0000000 011 040 116 141 155 145 040 061 054 126 141 154 165 145 040 061
\t N a m e 1 , V a l u e 1
0000020 174 042 116 141 155 145 040 062 042 054 126 141 154 165 145 040
| " N a m e 2 " , V a l u e
0000040 062 174 116 141 155 145 040 063 040 054 040 126 141 154 165 145
2 | N a m e 3 , V a l u e
0000060 040 063 040 011 012 011 040 116 141 155 145 040 061 054 126 141
3 \t \n \t N a m e 1 , V a
0000100 154 165 145 040 061 174 042 116 141 155 145 040 062 042 054 126
l u e 1 | " N a m e 2 " , V
0000120 141 154 165 145 040 062 174 116 141 155 145 040 063 040 054 040
a l u e 2 | N a m e 3 ,
0000140 126 141 154 165 145 040 063 040 011 012
V a l u e 3 \t \n
0000152
This was tested using a Korn shell, but should work with any POSIX-conforming shell.
Note that using printf '%s\n' "$var"
instead of echo $var
protects you in cases where the expansion of $var
contains any <tab> characters; adjacent <space> characters; and depending on what operating system and shell you're using, any backslash characters ( \
) that could yield unexpected transformations.