-1

I have a output stored in a variable that comes from a .jar script

Token is: XYZ123
Not found in page: 0
Not found in page: 1
Not found in page: 2
Found with ID : #14214733

Now I want to extract the ID after # i.e 14214733 and want to store it in another variable, how do I do that in bash?

EDIT: Solved using echo ${var##*#}

3
  • 2
    Could you echo your variable here? Wouldn't echo ${variable##*#} work ?
    – Jiri B
    Commented Mar 30, 2021 at 6:35
  • The echo $var produces the above output as a whole, now I want to get the last ID Commented Mar 30, 2021 at 7:00
  • I just tried the above code, and it worked like a charm. Thank you so much :) Commented Mar 30, 2021 at 7:18

2 Answers 2

2

With bash, capture it with a regular expression

output='Token is: XYZ123
Not found in page: 0
Not found in page: 1
Not found in page: 2
Found with ID : #14214733'

[[ $output =~ "Found with ID : #"([0-9]+) ]] && id=${BASH_REMATCH[1]}

echo $id    # => 14214733

In bash regular expressions, the literal text parts are quoted, and the regex-special stuff is not. Captured parts go into the BASH_REMATCH array.

0

One way would be:

sec_var=`cat ts.txt | grep -oE 'ID : #([0-9]+)' | cut -f2 -d '#'`
sec_var=`echo $first_var | grep -oE 'ID : #([0-9]+)' | cut -f2 -d '#'`

Also you can use grep "-z" option:

-z suppress newline at the end of line, substituting it for null character. That is, grep knows where end of line is, but sees the input as one big line.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.