2

How to extract whatever string comes after a matched pattern in Shell script. I know this functionality in Perl scripting, but i dont know in Shell scripting.

Following is the example,

Subject_01: This is a sample subject and this may vary

I have to extract whatever string that follows "Subject_01:"

Any help please.

Community
  • 1
  • 1
Senthil kumar
  • 965
  • 3
  • 16
  • 33
  • What shell are you using? Bourne? CSH? KSH88? [RC](http://plan9.bell-labs.com/sys/doc/rc.html)? – Graham May 15 '12 at 06:21
  • For extracting from a file, see also https://stackoverflow.com/questions/10358547/how-to-grep-for-contents-after-pattern – tripleee Apr 26 '21 at 12:53

1 Answers1

3

It depends on your shell.

If you're using shell or or (I believe) , then you can do fancy stuff like this:

$ string="Subject_01: This is a sample subject and this may vary"
$ output="${string#*: }"
$ echo $output
This is a sample subject and this may vary
$

Note that this is pretty limited in terms of format. The line above requires that you have ONE space after your colon. If you have more, it will pad the beginning of $output.

If you're using some other shell, you may have to do something like this, with the cut command:

> setenv string "Subject_01: This is a sample subject and this may vary"
> setenv output "`echo '$string' | cut -d: -f2`"
> echo $output
This is a sample subject and this may vary
> setenv output "`echo '$string' | sed 's/^[^:]*: *//'`"
> echo $output
This is a sample subject and this may vary
> 

The first example uses cut, which is very small and simple. The second example uses sed, which can do far more, but is a (very) little heavier in terms of CPU.

YMMV. There's probably a better way to handle this in csh (my second example uses tcsh), but I do most of my shell programming in Bourne.

ghoti
  • 45,319
  • 8
  • 65
  • 104
  • For cut, if you just want to drop the first field (in case there are colons in the rest of the string), use `-f2-` – glenn jackman May 15 '12 at 13:26
  • @glennjackman - true, thanks for pointing that out. That notation will return the rest of the line, even including whitespace around subsequent colons, though it still doesn't let us trim the whitespace at the start. – ghoti May 15 '12 at 13:45