Filtering matched content

Viewed 65

I want to Filter all content after match with the content and bring the first value after the "."

I have an output something like this:

Output:

product: 13.6.0.35_0

More specifically, I need only the first two digits and the first digit after the dot, remembering that we should not cling to the values in the issue, but rather on the method of filtering the content.

Expected:

13.6

I tried something like:

echo "product: 13.6.0.35_0" | grep -ow '\w*13\w*'
4 Answers

If you need to use grep with the current logic, you can use

echo "product: 13.6.0.35_0" | grep -ow '13\.[0-9]*' | head -1

where 13\.[0-9]* matches 13, . and zero or more digits (as whole word due to w option) and head -1 gets the first match.

You may also use sed or awk:

sed -En 's/.* ([0-9]+\.[0-9]+).*/\1/p' <<< "product: 13.6.0.35_0"
awk -F'[[:space:].]' '{print $2"."$3}' <<< "product: 13.6.0.35_0"

See the online demo.

The sed command matches any text up to space, then matches the space and captures the two subsequent dot-separated numbers into Group 1 (\1) and then the rest of the line is matched and replaced with Group 1 value that is printed (as the default line output is suppressed with -n).

In the awk command, the field separator is set to whitespace and . with -F'[[:space:].]' and the {print $2"."$3} part prints the second and third field values joined with a ..

A pure shell solution using the builtin read , Parameter Expansion and curly braces for command groupings.

echo "product: 13.6.0.35_0" | { read -r _ value; echo "${value%.*.*}" ; }

I reached the expected output, it's simple but it works:

var=$(echo "product: 13.6.0.35_0" | grep -Eo '[[:digit:]]+' | sed -n 1,2p)
echo ${var} | sed 's/ /./g'

You can also use cut:

 echo 'product: 13.6.0.35_0' | cut -d ' ' -f2 | cut -d '.' -f1-2
 13.6
Related