Extracting part of a string to a variable in bash

柔情痞子 提交于 2019-12-05 00:56:10

Here's another pure bash way. Works fine when your input is reasonably consistent and you don't need much flexibility in which section you pick out.

extractedNum="${testString#*:}"     # Remove through first :
extractedNum="${extractedNum#*:}"   # Remove through second :
extractedNum="${extractedNum%%:*}"  # Remove from next : to end of string

You could also filter the file while reading it, in a while loop for example:

while IFS=' ' read -r col line ; do
    # col has the column you wanted, line has the whole line
    # # #
done < <(sed -e 's/\([^:]*:\)\{2\}\([^:]*\).*/\2 &/' "yourfile")

The sed command is picking out the 2nd column and delimiting that value from the entire line with a space. If you don't need the entire line, just remove the space+& from the replacement and drop the line variable from the read. You can pick any column by changing the number in the \{2\} bit. (Put the command in double quotes if you want to use a variable there.)

Pure Bash using an array:

testString="abcdefg:12345:67890:abcde:12345:abcde"
IFS=':'
array=( $testString )
echo "value = ${array[2]}"

The output:

value = 67890

You can use cut for this kind of stuff. Here you go:

VAR=$(echo abcdefg:12345:67890:abcde:12345:abcde |cut -d":" -f3); echo $VAR

For the fun of it, this is how I would (not) do this with sed, but I'm sure there's easier ways. I guess that'd be a question of my own to future readers ;)

echo abcdefg:12345:67890:abcde:12345:abcde |sed -e "s/[^:]*:[^:]*:\([^:]*\):.*/\1/"

this should work for you: the key part is awk -F: '$0=$3'

NewVar=$(getTheLineSomehow...|awk -F: '$0=$3')

example:

kent$  newVar=$(echo "abcdefg:12345:67890:abcde:12345:abcde"|awk -F: '$0=$3')

kent$  echo $newVar 
67890

if your text was stored in var testString, you could:

kent$  echo $testString                                                                                                                                                     
abcdefg:12345:67890:abcde:12345:abcde
kent$  newVar=$(awk -F: '$0=$3' <<<"$testString")
kent$  echo $newVar                                                                                                                                                         
67890
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!