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?

4
  • Have you tried quoting the $FieldName in the echo? Commented Sep 10, 2012 at 10:38
  • that doesn't change anything. still the whitespace creates the same problem. Commented Sep 10, 2012 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. Commented Sep 10, 2012 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? Commented Sep 10, 2012 at 13:40

2 Answers 2

2

You don't need awk:

IFS=\;
set $FieldName
var=$@
Sign up to request clarification or add additional context in comments.

4 Comments

Is set -- $FieldName any better?
this solution is more elegant but it still can't solve the problem created by the whitespace
@abhayK: $9 will contain "ia <= ia2", whitespace and all. But when you expand the parameter, you need to quote it to protect that whitespace.
To join the string with , use this, i.e. IFS=, and var="$*".
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.