Parsing fields into variables

A record contains 50 fields separated by "~". I need to assign each of these fields to different variables. Following is the shell script approach I tried.

RECORD="FIELD1~FIELD2~FIELD3~FIELD4~FIELD5~...........~FIELD50"
VAR1=$(echo ${RECORD} | cut -d"~" -f 1)
VAR2=$(echo ${RECORD} | cut -d"~" -f 2)
VAR3=$(echo ${RECORD} | cut -d"~" -f 3)
.
.
.
.
.
VAR50=$(echo ${RECORD} | cut -d"~" -f 50)

Please share alternate approach to save these variables that might reduce the lines of code.

I'm using these variables further in the script for more operations around them.

Hello krishmaths,

As you haven't shown us the complete requirement here so little difficult to say how you wanted to use these 50 variables. But wanted to highlight here for these kind of requirements only we have array concept, here is an example for same where you could get an array with all the elements in the lines and if you wanted to use any specific position of that array's element you could do so.

awk '{num=split($0, array,"~");for(i=1;i<=num;i++){print A}}' Input_file

Also if above doesn't meet your requirements then please let us know more about requirement with sample inputs and sample expected output too.

Thanks,
R. Singh

1 Like

I wanted to use specific variable names for better readability. For example, the actual field name is more readable than an array name with index. Hence did not go for array.

Another approach I tried is using the

read

command.

echo ${RECORD} | read VAR1 VAR2 VAR3 

It works with space delimiter. I'm not sure how to handle this for other delimiters.

Hello krishmaths,

Could you please try and let me know if this helps you. Let's say following is the Input_file.

cat  Input_file
A~B CDR~rsbkjdewdj @!!!~deiiugewiuewn

Then following is the code.

while IFS="~" read -r name dept cool; do
     echo $dept
done < "Input_file"

Output will be as follows then. Similarly we could take all variable values from it.

B CDR

Thanks,
R. Singh

1 Like

Thanks for your inputs. I tried the following and it worked. I needed to read from variable and not from a file.

RECORD="F1~F2~F3"
echo ${RECORD} | IFS="~" read VAR1 VAR2 VAR3
echo $VAR1 $VAR2 $VAR3

Output:

F1 F2 F3

Got a recent bash providing "here strings"? Try

RECORD="F1~F2~F3"
IFS="~" read VAR1 VAR2 VAR3 <<< $RECORD
echo $VAR1 $VAR2 $VAR3
F1 F2 F3