Shell脚本 - 读取列值并存储到变量的最佳方法?

时间:2016-09-10 04:33:02

标签: bash shell variables unix

我将下面的批处理开始日期,开始时间,结束日期,结束时间和状态存储在名为line的变量中:

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

我需要将每个coulmn值存储到各种变量:batch_name,start_date,start_time,end_date,end_time,status。

这样做的一种方法是使用awk,但如果cloumns的数量非常大,看起来很混乱:

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}')"

另一种方法是使用while循环,但它不会在循环外保留值,因为while循环生成子shell:

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

PS:
我有一个存储许多批次状态的文件。我必须遍历每一行,并根据状态,结束时间等,需要做一些处理:

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

我的最终剧本如下:

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

1 个答案:

答案 0 :(得分:1)

使用bash:

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

如果您想使用管道,请启用bash的选项lastpipe以在子shell中运行while

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