【问题标题】:Shell script- best way to read column values and store to variable?Shell脚本-读取列值并存储到变量的最佳方法?
【发布时间】:2016-09-10 13:12:14
【问题描述】:

我将以下批次开始日期、开始时间、结束日期、结束时间和状态存储在一个名为 line 的变量中:

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

我需要将每列值存储到各种变量中: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循环之外保留值,因为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

【问题讨论】:

  • while read -r batch_name start_date start_time end_date end_time status; do echo "do procesing here"; done < batch_status.txt
  • 这在 bash 中不起作用,因为 while 循环会生成一个子 shell,因此变量值不会反映在 while 循环之外
  • 不,while 循环不会产生任何子外壳,但管道会创建一个子外壳。
  • 感谢指正。但是当我尝试在 while 循环之外显示值时,无法看到它们的值
  • 不确定什么不适合你,但while read -r batch_name start_date start_time end_date end_time status; do declare -p batch_name start_date start_time end_date end_time status; done < batch_status.txt 对我来说很好。

标签: bash shell variables unix


【解决方案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

【讨论】:

    猜你喜欢
    • 2019-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多