Search code examples
grep

How to grep the first string delimited by ''


How to grep the first string within '' in a text file? in:

path: '', redirectTo: '/login', pathMatch: 'full' },
path: 'login', component: LoginComponent },
path: 'registration',
path: 'employees',
path: 'recruitment',
path: 'work',

out:


login
registration
employees
recruitment
work

I tried:

grep -Po "path: '\K.*'" in

Solution

  • You might use gnu-awk with a regex and a capture group, capturing optional chars other than ' between 2 ' chars

    awk 'match($0, /path: \047([^\047]*)\047/, a) {print a[1]}' file
    

    Output

    [empty line] <--
    login
    registration
    employees
    recruitment
    work
    

    If you are using grep -P for a Perl compatible regular expression with a negated character class [^']* and a lookahead , but that does not print the empty line:

    grep -Po "path: '\K[^']*(?=')" file
    

    Output

    login
    registration
    employees
    recruitment
    work