-1

I have a string variable Short_name="This_is_test_string"

I want to output the substring test_string from the Short_name variable using sed.

midori
  • 4,807
  • 5
  • 34
  • 62
Rock
  • 157
  • 1
  • 3
  • 13
  • Are you saying you have a variable named `Short_name` whose value is `"This_is_test_string"` or a variable whose value is `Short_name="This_is_test_string"` or something else? Why do you need to use sed? – Ed Morton Jan 21 '16 at 23:58

2 Answers2

1

Like this:

echo 'Short_name="This_is_test_string"' | sed 's/.*_is_//;s/"//'

Breaking it down:

s           -- substitute command
/           -- delimiter
.*_is_      -- match this
                 .*     -- any character (.), as many as possible (*)
                 _is_   -- these 4 exact characters
/           -- delimiter
(nothing)   -- what to replace any match with
/           -- delimiter
;           -- end this command, start another
s           -- substitute command
/           -- delimiter
"           -- match this character
/           -- delimiter
(nothing)   -- what to replace any match with
/           -- delimiter

 

[EDIT]

The key is figuring out which pattern matches your needs (which I don't yet have a good understanding of). Perhaps this:

... | sed 's/.*[[:<:]]is[ _]*//;s/"//'

The "tricky bit" here is [[:<:]] which is a "zero width assertion" (in this case "beginning of word") which keeps us from doing the wrong thing on inputs like this:

echo 'string2=is  this it"' | sed 's/.*[[:<:]]is[ _]*//;s/"//'

(by keeping us from matching the "is" in "this")

John Hascall
  • 9,176
  • 6
  • 48
  • 72
  • I just tried using below way, string="this_is_my_test_name" final=$(echo ${string} | sed 's/^.*is_//;') which gives expected output. but, if scenario is like, string2=is then below code is not working, final=$(echo ${string} | sed 's/^.*${string2}_//;') how to use variable string2? – Rock Jan 21 '16 at 18:58
  • got solution, final=$(echo ${string} | sed 's/^.*'$o_string'_//;') – Rock Jan 21 '16 at 19:07
0

You don't need sed. Bash parameter expansion will do:

$ Short_name="This_is_test_string"
$ echo "${Short_name##*_is_}"
test_string

That removes everything from the beginning of the string up to and including the last "_is_"

glenn jackman
  • 238,783
  • 38
  • 220
  • 352