Search code examples
awk

How to get the string prefixed with "Mat" within curly braces {} and add a comma to output


How to get the string prefixed with "Mat" within curly braces {} and print with the addition of a comma? e.g. in:

import { MatSidenavModule } from '@angular/material/sidenav';
import { MatToolbarModule } from '@angular/material/toolbar';
import { RouterOutlet } from '@angular/router';

out:

MatSidenavModule,
MatToolbarModule,

I tried:

awk -F"[{}]" 'BEGIN {/Mat/} {gsub(/ /, "", $2); print $2","}' in

GNU Awk version is 5.0.1.


Solution

  • The BEGIN block should contain code which you want to run before the main script. I'm guessing you want

    awk -F"[{}]" '/Mat/ {gsub(/ /, "", $2); print $2","}' in
    

    A more precise condition would be $2 ~ /Mat/ to ensure that you don't trigger on stray matches in other fields (or even use /^[ \t]*Mat/ if you always expect it to match at the beginning of the field).

    awk -F"[{}]" '$2 ~ /^[ \t]*Mat/ {
        gsub(/[ \t]+/, "", $2);
        print $2 ","}' in
    

    Using Awk for this sort of thing basically requires the input to use predictable formatting, and not e.g. arbitrarily add a newline after import {. In the limit, you need a parser for the language you are processing (Javascript?)