Operating System - HP-UX
1834412 Members
1598 Online
110067 Solutions
New Discussion

How can I delimit a string and arrange them in rows ??

 
Chris Fung
Frequent Advisor

How can I delimit a string and arrange them in rows ??

Hi all,

I encounter a difficult in delimiting an unknow strings (i.e dynamica changes in length) and arrange them in a row format !!

E.g. I have a string like:

a, b, c, d, e, f, g, ....etc.

I would like to arrange them like:

a
b
c
d
e
f
g
.
.
.
etc.

I've try to write a simple script with while loop and awk ....but was in vain!! Any ideas?? Appreciate if you can help solve this problem.

Thanks,

Chris
5 REPLIES 5
James R. Ferguson
Acclaimed Contributor

Re: How can I delimit a string and arrange them in rows ??

Hi Chris:

Try this:

echo "a, b, c, d, e, f"|tr -d " "|tr -s "," "\n"

Regards!

...JRF...

James R. Ferguson
Acclaimed Contributor

Re: How can I delimit a string and arrange them in rows ??

Hi (again) Chris:

If you wanted to preserve blanks (whitespace) between the comma-delimited fields, as in a person's name, drop the '-d " "' from the suggestion I made above:

# echo "a, b, c, d, e, f"|tr -s "," "\n"

Given a file of comma delimited fields, but with trailing whitespace, e.g. "my name ," then remove the *trailing* whitespace :

# cat myfile|tr -s "," "\n"|sed -e 's/[ \t]*$//'

For timming *leading* whitespace, e.g. " my name," :

# cat myfile|tr -s "," "\n"|sed -e 's/^[ \t]*//'

...and to trim both trailing and leading whitespace, e.g. " my name ," :

# cat myfile| cat /tmp/myfile |tr "," "\n"|sed -e 's/^[ \t]*//' -e 's/[ \t]*$//'

NOTE! In all the example above with { \t] type a "[", a space (blank), a TAB chararacter, and a "]".

Regards!

...JRF...
Heiner E. Lennackers
Respected Contributor

Re: How can I delimit a string and arrange them in rows ??

Or try this:

echo "a, b, c, d ..." | tr ',' ' ' | xargs -n1

Heiner
if this makes any sense to you, you have a BIG problem

Re: How can I delimit a string and arrange them in rows ??

Use paste !!
Daimian Woznick
Trusted Contributor

Re: How can I delimit a string and arrange them in rows ??

Sticking with the awk and while loop concept, try the following...

Please forgive the syntax, I'm not currently at a terminal to test.


echo $string > string.file

counter=1
test_var=TEST

while [ ! -z $test_var ]
do

echo $test_var >> temp.file

test_var=`awk -F, '{print $'$counter'}' string.file`

let counter=$counter+1

done

Use cat to check the temp.file. The $counter in the awk statement may need double quotes.