Grab characters following grep

Hi all,

I'm trying to gather data directly following a keyword in a file but I have no guarantee where it will appear in said file so I can't use cut or anything else that assumes it will be located at a certain position. If anyone has any suggestions I'd be grateful. Here is an example of the line:
MODStandard , Building=3A 1234, Syntax ID=3B=

In this example I want to search for the keyword "Building" and then grab the four characters "1234" that appear to the right of it.

Thanks in advance.

$ echo "MODStandard , Building=3A 1234, Syntax ID=3B=" | sed "s/.*Building[^,]*\([^, ]\{4\}\),.*/Building=\1/"
Building=1234

Thanks but I can't get it to function in production. Running it as:
grep Building file.dat | sed "s/.*Building[^,]\([^, ]\{4\}\),./Building=\1/"

...just spits out the whole line instead of just the section like your example shows.

Am I not understanding the syntax correctly?

#!/bin/bash
# bash 3++
while read -r LINE
do
  case "$LINE" in
    *Building*)
        LINE=${LINE##*Building=}
        echo ${LINE%%,*};;
  esac
done <"file"

awk '/Building/ {sub(/,/,"",$4); print $4}' urfile

Can you explain the syntax to me? Thanks.

awk splits up the input line into tokens $1, $2, $3, ... etc.; so for this line

MODStandard , Building=3A 1234, Syntax ID=3B=

$4 equals the string "1234,".

awk's "sub" function performs a replacement on a target string. So

sub(/,/,"",$4); 

replaces the comma (in the regex pattern /,/) by zero-length string (2nd argument "") in the target string $4 (which is "1234,"). Thus $4 turns into "1234" which is then printed.

The construct

/Building/ {<action>}

performs the action <action> only for lines that have the literal "Building" in them.

A Perl one-liner for the same problem would be:

$
$ cat f2
blah
MODStandard , Building=3A 1234, Syntax ID=3B=
blah blah
$
$ perl -lne '/Building.*? (\d+),/ and print $1' f2
1234
$
$

HTH,
tyler_durden

Yes it does. Thanks for explaining that so thoroughly. :b:

And thanks to everyone for their suggestions. :smiley: