简体   繁体   English

如何在bash脚本中获取shell命令的中间值

[英]How can I get the middle value of a shell command in bash script

I am writing a bash shell script. 我正在编写bash shell脚本。 In there, I execute a command and save the output to a variable. 在这里,我执行命令并将输出保存到变量。 The value is like this: 该值是这样的:

0x34f0020d4         4 0x434346000 test_string

How can I parse and save the value of the 3rd string (ie 0x434346000), assume the value is separated by space or tab? 假设值由空格或制表符分隔,我如何解析和保存第三个字符串的值(即0x434346000)?

Put your command which gives the above output in this fashion: 将您的命令以这种方式提供上述输出:

x=($(your command))
$ echo ${x[2]}
0x434346000

The output of the command is being stored in an array "x", and hence the index 2 of the array contains the 3rd element. 命令的输出存储在数组“ x”中,因此数组的索引2包含第3个元素。

Use the shell read command: 使用shell read命令:

read first second third rest <<< "$line"
echo $third

Here's one way using awk : 这是使用awk的一种方法:

var=$(echo "$string" | awk '{ print $3 }')

Test: 测试:

echo "$var"

Results: 结果:

0x434346000

You can also use the cut command. 您也可以使用cut命令。 echo "axbxc" | 回声“ axbxc” | cut -f 2 -d "x" gives b 切-f 2 -d“ x”给出b

Use an array to index values: 使用数组索引值:

arr=("0x34f0020d4         4 0x434346000 test_string")
echo "${arr[2]}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM