Sunday, May 5, 2024
3
rated 0 times [  3] [ 0]  / answers: 1 / hits: 2939  / 3 Years ago, fri, may 28, 2021, 12:37:27

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.


More From » command-line

 Answers
0

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.


[#746] Friday, May 28, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nosaurindb

Total Points: 266
Total Questions: 113
Total Answers: 120

Location: Ecuador
Member since Tue, Jul 26, 2022
2 Years ago
;