Extracting part of a string to a variable in bash

Steven Cragg picture Steven Cragg · Apr 9, 2013 · Viewed 48.9k times · Source

noob here, sorry if a repost. I am extracting a string from a file, and end up with a line, something like:

abcdefg:12345:67890:abcde:12345:abcde

Let's say it's in a variable named testString the length of the values between the colons is not constant, but I want to save the number, as a string is fine, to a variable, between the 2nd and 3rd colons. so in this case I'd end up with my new variable, let's call it extractedNum, being 67890 . I assume I have to use sed but have never used it and trying to get my head around it... Can anyone help? Cheers

On a side-note, I am using find to extract the entire line from a string, by searching for the 1st string of characters, in this case the abcdefg part.

Answer

Fritz G. Mehner picture Fritz G. Mehner · Apr 9, 2013

Pure Bash using an array:

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

The output:

value = 67890