Home > Software engineering >  How to get string between two characters in bash
How to get string between two characters in bash

Time:11-02

How to get string between two characters like:

https://hello.world.example.com

to get hello between // and . I try the following:

echo 'https://hello.world.example.com' | awk -F[/.] '{print $2}'

looks like it can be parsed

how to parse the string between // and .?

thanks!

CodePudding user response:

Bash itself has string manipulation procedures.

Try:

s='https://hello.world.example.com'


s1="${s#*//}"   # Deletes shortest match of *// from front of $s
s2="${s1%%.*}"  # Delete longest match of .* (ie, from first .) in s1

echo "$s2"
# hello

In the first case, #*// is the shortest match from the front of the string up to and including //.

In the second case, %%.* matches the longest sub string from the literal '.' to the end of the string represented by *

You can read more here.


Or use sed:

echo "$s" | sed -E 's/^[^/]*\/\/([^.]*)\..*/\1/'
                    ^                              Substitute
                      ^                            Start of string
                         ^                         Not a /
                            ^                      Two literal //
                                ^                  Capture that
                                        ^          Literal .
                                          ^        The rest of the string
                                            ^      The replacement 
                                                   is the captured word     

CodePudding user response:

Your original awk command will place the string hello in column 3 instead of 2.

Using your awk with a minor change, the string will now be in column 2

$ echo 'https://hello.world.example.com' | awk -F"[/.] " '{print $2}'
hello

Or using sed

$ echo 'https://hello.world.example.com' | sed -E 's~[^/]*/ |\..*~~g'
hello
  •  Tags:  
  • bash
  • Related