How i can sed save pattern matches to variables and do something with it? eg

$ echo "string_4.3.2" | sed 's/^string_\([0-9]\)\.\([0-9]\)\.\([0-9]\)$/\1 \2 \3/'

output "4 3 2" but I want to pass variables to function eg

do_something() {
    echo $1
    echo $2
    echo $3
    # .....
    # .....
}

string="string_4.3.2"
if [[ $string =~ `sed ??????` ]]; then
    do_something "$1" "$2" "$3"
fi

Matched numbers need pasing to method "do_something"

Dani AI

Generated

Good call by — using bash's built‑in regex and BASH_REMATCH is the simplest, safest approach instead of trying to force sed into [[ ... =~ ... ]]. A couple of compact, practical alternatives and a few pitfalls follow.

s='string_12.34.5'
regex='^string_([0-9]+)\.([0-9]+)\.([0-9]+)$'

if [[ $s =~ $regex ]]; then
  major=${BASH_REMATCH[1]}
  minor=${BASH_REMATCH[2]}
  patch=${BASH_REMATCH[3]}
  do_something "$major" "$minor" "$patch"
fi

Notes: BASH_REMATCH[0] is the whole match; BASH_REMATCH[1]..n are the capture groups. Do not quote the regex expansion in [[ ... =~ ... ]] (quoting makes it a literal string). Escape literal dots (\.) and use + (or {}) if multi‑digit components are needed.

s='string_4.3.2'
suffix=${s#string_}       # remove known prefix
IFS=. read -r major minor patch <<< "$suffix"
do_something "$major" "$minor" "$patch"

This variant avoids regex entirely: strip the prefix, split on . with read, and pass the three fields to the function. It is simple and fast, but assumes a fixed prefix and dot separators.

Quick tips: for POSIX /bin/sh use awk or cut (bash‑only features above will not work). Avoid spawning external tools in tight loops for performance. Always quote variable expansions when calling functions to preserve whitespace.

Thanks to everyone who tried to help. I found solution:

string="string_4.3.2"
if [[ $string =~ ^string_([0-9])\.([0-9])\.([0-9])$ ]]; then
    do_something "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" "${BASH_REMATCH[3]}"
fi
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.