0

I used the following line to create an array of fields from a string:

var=$(echo $FieldName | awk -F";" '{print $1,$2,$3,$4,$5,$6,$7,$8,$9}')

$FieldName is a string having fields separated by semicolon.

When $FieldName contains string without whitespace it behaves properly. The problem is when it contains any whitespace character embedded then the script treats the whitespace as newline.

e.g.:

$FieldName = aa;bcd;cal;da;ea;fa;ga;ha;ia

gives [aa,bcd,cal,da,ea,fa,ga,ha,ia] which is as expected.

But $FieldName = aa;bcd;cal;da;ea;fa;ga;ha;ia <= ia2

gives [aa,bcd,cal,da,ea,fa,ga,ha,ia] , [<=, , , , , , , , ] and [ia2, , , , , , , , ]

Any ideas?

Sicco
  • 6,167
  • 5
  • 45
  • 61
Abinash Koirala
  • 977
  • 1
  • 9
  • 18
  • Have you tried quoting the `$FieldName` in the `echo`? – Thor Sep 10 '12 at 10:38
  • that doesn't change anything. still the whitespace creates the same problem. – Abinash Koirala Sep 10 '12 at 10:57
  • Like @chepner also implies, the fundamental problem is probably that you are using `echo $value` instead of `echo "$value"` with proper double quotes. Always quote your variable interpolations, unless you specifically require the shell to perform word splitting and wildcard expansion on the value. – tripleee Sep 10 '12 at 13:27
  • I think the problem is what you do with `$var` -- what do you do with `$var`? Is `$var` quoted when you use it later in your script? Are you using `printf`? – glenn jackman Sep 10 '12 at 13:40

2 Answers2

2

You don't need awk:

IFS=\;
set $FieldName
var=$@
perreal
  • 94,503
  • 21
  • 155
  • 181
  • Is `set -- $FieldName` any better? – fork0 Sep 10 '12 at 10:28
  • this solution is more elegant but it still can't solve the problem created by the whitespace – Abinash Koirala Sep 10 '12 at 10:46
  • 2
    @abhayK: `$9` will contain "ia <= ia2", whitespace and all. But when you expand the parameter, you need to quote it to protect that whitespace. – chepner Sep 10 '12 at 13:05
  • To join the string with `,` use [this](http://stackoverflow.com/questions/1527049/bash-join-elements-of-an-array), i.e. `IFS=,` and `var="$*"`. – Thor Sep 11 '12 at 05:37
1

You seem to be trying to change the delimiter of $FieldName, in that case use awk like this:

echo "$FieldName" | awk -v FS=',' -v OFS=';' 1

The 1 executes the default block: { print $0 }.

Or tr:

echo "$FieldName" | tr ';' ','    

Output:

aa,bcd,cal,da,ea,fa,ga,ha,ia <= ia2
Thor
  • 45,082
  • 11
  • 119
  • 130