Extracting part of a string to a variable in bash Extracting part of a string to a variable in bash bash bash

Extracting part of a string to a variable in bash


Pure Bash using an array:

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

The output:

value = 67890


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.)


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/"