1

I have a string 36K total,TOO_MANY_NEWLINE_IN_TEXT_tABLE. From this string i need only 36.

is that possible?

5
  • 1
    What do you mean? Is your string static and you know where the position of "36" is? Or you want any number in your dynamic string? Commented Oct 8, 2017 at 13:08
  • 1
    Or you just want firs 2 characters in any string? Commented Oct 8, 2017 at 13:09
  • i need first 2 characters of a sting Commented Oct 8, 2017 at 13:10
  • @RajasekarKaliyamoorthi It's called a string, not sting. Commented Oct 8, 2017 at 13:11
  • echo '36K total,TOO_MANY_NEWLINE_IN_TEXT_tABLE' | sed 's/[^0-9].*//'? Commented Oct 8, 2017 at 13:34

4 Answers 4

2

As described in https://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion, you can write

echo "${foo:0:2}"

to output the first two characters of a variable foo.

Sign up to request clarification or add additional context in comments.

Comments

0

You could also try this:

echo "36K    total,TOO_MANY_NEWLINE_IN_TEXT_tABLE" | grep -oEi '([0-9])+'

2 Comments

Why use the -i flag?
@melpomene man grep. I guess you don't need to ignore case for numbers. I thought it would be nice to include -i, in case, he uses it to capture values other integers.
0

To extract the leading number (of variable length) from a string in pure bash (without any external tools), you can use the =~ operator (extended regex match) inside the conditional expression [[ .. ]]:

$ line='36K    total,TOO_MANY_NEWLINE_IN_TEXT_tABLE'
$ [[ $line =~ [0-9]* ]] && echo "$BASH_REMATCH"
36

Comments

0

You have a delimiter; the letter K separates the first desired substring, 36, from the rest of the string.

$ str="36K    total,TOO_MANY_NEWLINE_IN_TEXT_tABLE"
$ IFS=K read num rest <<< "$str"
$ echo "$num"
36

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.