1
TEXT='Random text 1 and some more random'
TEXT1='Random 19 and more'
TEXT='Anything 7 text text text'

I wanted to get everything before the numbers with the numbers included.

Right now, I am able to get the text without the numbers, like so:

echo "${TEXT// [0-9]*/}"

My question is: is there a way to get what I want with pure Bash built in, like this I am using?

3
  • Why not just echo $TEXT | awk '{print $1,$2,$3}' or if you want the pipes, echo $TEXT | awk '{print "|"$1,$2,$3"|"}'? Aug 24, 2019 at 16:08
  • I took off the pipes.
    – Roger
    Aug 24, 2019 at 19:40
  • And edited the question giving more examples.
    – Roger
    Aug 24, 2019 at 19:45

3 Answers 3

1

Try this:

echo "'${TEXT// [^0-9]*/}'" "'${TEXT1// [^0-9]*/}'"

Output:

'Anything 7' 'Random 19'

Note that if the string has no numbers, this code will remove everything past the first space.

1

If there is only one cluster of digits you can do it in two steps (in one expansion):

  • Remove the longest leading text that ends in a number.

    $ text='Random 923 and more'
    $ echo "'${text##*[0-9]}'"
    ' and more'
    
  • Then, remove that selected trailing text from the original string:

    $ echo "'${text%"${text##*[0-9]}"}'"
    'Random 9'
    

That works if the trailing text has no additional numbers.

If could there be several clusters of digits, and you want only the first one, it becomes a bit longer and requires two additional variables.

$ text='Random 945 and more 752 numbers'
$ lead=${text%%[0-9]*}
$ trail=${text#"$lead"}
$ echo "'$lead${trail%%[!0-9]*}'"
'Random 945'
0

You could use the bash shell's regular expression matching capability:

$ TEXT='Random text 1 and some more random'

$ [[ $TEXT =~ ^[^0-9]*[0-9] ]] && printf '%s\n' "$BASH_REMATCH"
Random text 1

where ^[^0-9]*[0-9] matches zero or more non-digits followed by a digit, anchored to the start of the string

3
  • Thank you. I edited the question.
    – Roger
    Aug 24, 2019 at 19:53
  • Following this leed, I'd use: echo "grep -o '^[^0-9]*[0-9]' <<< "$TEXT". But I am seeking a pure Bash built in...
    – Roger
    Aug 24, 2019 at 20:23
  • I'd love that something like this would work: cut -d'[0-9]' -f1 <<< "$TEXT"... But it does not.
    – Roger
    Aug 24, 2019 at 20:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .