I am new to scripting

I want to parse a string in a loop
eg A:B:C:D
E:F:G:H
and put them in different variable
attr1 = A
attr2 = B
attr3 = C
attr4 = D
.
.
/* do processing with attr1, attr2, attr3 and attr4 */

then go to next line E:F:G:H and again assign attr1/attr2/attr3/attr4 with E,F,G and H

Strings I am reding from file line by line. In a line, string can be of any size
for example
A:B:C:D
E:F:G:H
I:J:K:L:M:N

After reading one line I want to traverse it till new line charater and put strings in attr.. variables and then read next line and so on

Here is script which I am using but it assumes four string in a line I want to traverse a line till new line.

while read line; do
attr1=`echo $line | cut -d: -f1`
attr2=`echo $line | cut -d: -f2`
attr3=`echo $line | cut -d: -f3`
attr4=`echo $line | cut -d: -f4`
echo $attr1 $attr2 $attr3 $attr4
done < inputfile


Could you please help me out

Recommended Answers

All 2 Replies

I'm not familiar with shell scripting (I know I should be), but I am good with other programming languages. Here's pseudocode for your problem:

index=0

while mychar != null:
   mychar = getchar(index, thestring)
do parsing here
.
.
.
   index= index + 1
end while

Hope this makes sense

I would do this in Korn Shell. I haven't tested it on bash but it should do the same. It is POSIX shell syntax.

while read line ; do
set -A attr $(echo $line | tr ':' ' ')
echo ${attr
[*]}
done

The array elements are indexed from 0 to ${#attr
[*]} - 1

That is ${attr[0]}, ${attr[0]}, ${attr[0]} ... ${attr[$((${#attr
[*]}-1))]}

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.