将命令的输出传递给shell脚本中的变量

时间:2014-09-04 03:25:31

标签: bash shell unix

我正在尝试将命令的输出传递给变量。 试过很多报价但没有成功,请检查

我正在从$ line中的文件中读取输入并对其进行处理,尝试将输出保存在变量a。

set a="$($line|cut -d'-' -f 2|cut -d'.' -f 1|sed 's/[^0-9]*//g’)"

4 个答案:

答案 0 :(得分:2)

一些事情。

首先,您不应该使用set,而不是环境变量。

其次,除非$line是实际的命令,,否则你需要回应它。

第三,关于sed命令的结束引用是错误的类型,而不是'

所以,你应该使用:

a="$(echo $line|cut -d'-' -f 2|cut -d'.' -f 1|sed 's/[^0-9]*//g')"

您可以在以下成绩单中看到这一点:

pax> line="date=2014.09.05-time=12.34.56"
pax> a="$(echo $line|cut -d'-' -f 2|cut -d'.' -f 1|sed 's/[^0-9]*//g')"
pax> echo $a
12

抓取第二个-分隔字段(time=12.34.56),然后抓取第一个.分隔字段(time=12),然后删除所有非数字字段开始只给12

答案 1 :(得分:1)

使用echo

a="$(echo $line|cut -d'-' -f 2|cut -d'.' -f 1|sed 's/[^0-9]*//g')"

答案 2 :(得分:0)

假设$filename是该文件的名称,您正在阅读,您几乎就在那里:

a="$(<$filename cut -d'-' -f 2|cut -d'.' -f 1|sed 's/[^0-9]*//g')"

问题是:

  • 调用set,这是无用的
  • 错误读取文件($line执行,您想要从中读取。
  • //g之后的错误引用 - 您想要一个简单的单引号('

答案 3 :(得分:0)

使用shell本身提供的参数扩展工具,而不是使用长的多进程管道。

tmp1=${line#*-}  # Remove everything up to and include the first -
tmp2=${tmp1%%.*} # Remove everything from the first . onward
a=${tmp2//[!0-9]} # Remove anything that isn't a numerical digit

如果您正在读取文件,则可以将第一步折叠到读取命令本身

while IFS=- read first second rest; do
    tmp=${second%%.*}
    a=${tmp//[!0-9]}
done

定义一个正则表达式来捕获你想要的字符串部分也可能更简单(一个示例行将有助于定义这样的正则表达式)。

[[ $line =~ $regex ]] && a=${BASH_REMATCH[1]}  # Assuming the first capture group