How to grep a string from a file starting from a pattern and ending from a pattern

I have this script:

#!/bin/bash
user=datab-admin-role
allusers="datab-admin-111role datab-admin-112role datab-admin-113role "
if(...)
then..
...

I want to grep only the first occurrence of a string starting with datab and ending with role in a variable.

What I am trying is:

 sed -n '/datab/,/role/p' filename

But it returns all the strings with datab and also it returns it as:

user=datab-admin-role

I want it to only return datab-admin-role and assign it to a variable.

0

3 Answers

I would use grep for this:

grep -o -m 1 'datab[A-Za-z0-9-]*role' filename 

The -o flag means only returned the part of the line that matches the pattern, not the whole line.

The -m 1 flag means return the first occurrence only.

The pattern is anything starting with datab followed by only letters, digits and hyphens,, then role, which is what I assume you want, since you don't just want a longer string with space or punctuation or something else inside.

To assign to a variable:

myvar="$(grep -o -m 1 'datab[A-Za-z0-9-]*role' filename )"

But I'm sure there's a way to do it with sed as well.

I'd likely use the posted grep solution however you can do it in sed using a capture group.

In sed, /pattern1/,/pattern2/ addresses a range of lines between matching patterns - if you want to match between patterns on a single line you need something like

sed -n '/.*\(datab.*role\).*/{s//\1/p;q;}' filename

where the \( and \) define a capture group, and \1 back-references it, omitting any leading .* and trailing .* characters to simulate grep's -o or --only-matching flag (and we quit after the first match to simulate grep's -m1).

Or using GNU sed

sed -En 's/.*(datab.*role).*/\1/p;T;q' filename

(here the T branches past the q until the s succeeds).

You can change (datab.*role) to (datab[A-Za-z0-9-]*role) for a more restrictive match if necessary.

1

A perl approach:

$ perl -lne 'if(/datab.+?role/){print $&; exit}' file
datab-admin-role

The -l adds a newline to every print call and strips trailing newlines from each input line. The -n means "read the input file line by line and apply the script given by -e to each line".

The script itself tries to match datab then the shortest possible string (.+?) until the first role. If this is found, we print what was matched (the special variable $&) and exit.

To store in a variable, just do:

var=$(perl -lne 'if(/datab.+?role/){print $&; exit}' file)
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like