penguin
penguin

Reputation: 133

Shell script- best way to read column values and store to variable?

I have below batch start date,start time,end date,end time and status stored in a variable called line :

echo "$line"
batch1 09/09/2016 15:12:00 09/09/2016 16:00:00 success

I need to store each coulmn values to various variables : batch_name,start_date,start_time,end_date,end_time,status.

one way of doing it is using awk, but looks cluttered if number of cloumns is very large:

batch_name="$(echo $line|awk '{ print $1}')"
start_date="$(echo $line|awk '{ print $2}')"
start_time="$(echo $line|awk '{ print $3}')"
end_date="$(echo $line|awk '{ print $4}')"
end_time="$(echo $line|awk '{ print $5}')"
status="$(echo $line|awk '{ print $6}')"

Another way is using while loop, but it wont retain values outside while loop since while loop spawns a sub-shell:

echo "$line"|while read batch_name start_date start_time end_date end_time status;do
echo ""
done 

PS:
I have a file which stores status of many batches. I have to iterate through each line and based on status,end time etc. , need to do some processing :

cat batch_status.txt
batch1 09/09/2016 15:12:00 09/09/2016 16:00:00 success
batch2 08/09/2016 09:00:08 09/09/2016 01:56:12 inprogress
batch3 08/09/2016 07:15:28 08/09/2016 01:46:22 failure

My final script will look like :

cat batch_status.txt|while read line;do
 #read LINE and store each column values to corresponding variable (best way to do it?)
 #do processing based on batch_name,start_date,start_time,end_date,end_time,status
done

Upvotes: 0

Views: 3166

Answers (1)

Cyrus
Cyrus

Reputation: 88776

With bash:

read -r batch_name start_date start_time end_date end_time status <<< "$line"

If you want to use a pipe, enable bash's option lastpipe to run while not in a subshell:

line='batch1 09/09/2016 15:12:00 09/09/2016 16:00:00 success'
shopt -s lastpipe
echo "$line" | while read batch_name start_date start_time end_date end_time status; do echo $status; done

Upvotes: 1

Related Questions