简体   繁体   中英

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

I am writing a bash shell script. 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?

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.

Use the shell read command:

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

Here's one way using awk :

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

Test:

echo "$var"

Results:

0x434346000

You can also use the cut command. echo "axbxc" | cut -f 2 -d "x" gives b

Use an array to index values:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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