Bash Cut,Sed还是Trim?

时间:2015-09-08 17:55:41

标签: bash

我需要运行一个程序并回显最终结果,并将其保存在变量中。我目前有

myvar="(`echo 34 | ./prog | cut -d "." -f2`)"

问题是显示整个字符串。例如,我看到

34 hello the result is: 343

我只需要将343保存在变量中。我通过34的原因是因为我想在跑步时传递34。我无法保存343。当我回显变量时,整个变量显示在屏幕上......

1 个答案:

答案 0 :(得分:3)

使用任何外部工具 - cutsed等 - 是愚蠢的; bash可以更有效地内置这样做:

#!/bin/bash
#      ^- must be /bin/bash for <<< to work; if /bin/sh, then myvar=$(echo 34 | ./prog)

myvar="$(./prog <<<34)"  # capture the full output of running ./prog with 34 on its stdin
myvar=${myvar##*: }      # delete everything up to and including the last ": "
echo "$myvar"            # show your results

请参阅: