1

I have the following array inside a program:

  ... #code
  $packages = [ 
    'git',        # version control
     ...
    'iftop',      # monitor network usage by ip
    'iotop',      # monitor io usage
  ]
  ... #more code

I want to use awk to print lines from the first occurrence of $packages to the first ending ], after the occurrence of $packages.

How can I do this?

2 Answers2

1

Iterate over the records, keep an identifier for $packages, print lines when the identifier is set, and exit after printing when you find next ]:

awk '/\$packages/ {c=1; print; next} /\]/ {print; exit}; c{print}'

Example:

% cat file.txt 
  ... #code
  $packages = [ 
    'git',        # version control
     ...
    'iftop',      # monitor network usage by ip
    'iotop',      # monitor io usage
  ]
  ... #more code

  ... #code
  $packages = [ 
    'git',        # version control
     ...
    'iftop',      # monitor network usage by ip
    'iotop',      # monitor io usage
  ]
  ... #more code

% awk '/\$packages/ {c=1; print; next} /\]/ {print; exit}; c{print}' file.txt   
  $packages = [ 
    'git',        # version control
     ...
    'iftop',      # monitor network usage by ip
    'iotop',      # monitor io usage
  ]
heemayl
  • 56,300
1

We use the range operator , of sed to select the range of lines we are interested in. For this scenario, the range begins with the string $package and ends with ] (on different lines).

First we reject any lines outside of the range, /\$package/,/]/!d and then from the range we print them all (due to the implicit printing of the pattern space property of sed) BUT quit as soon as the line with the string ] is met. it implies, we have printed to stdout the first of the ranges /\$package/,/]/

sed -e '/\$packages/,/]/!d; /]/q' yourfile
sed -n '/\$packages/,/]/p; /]/q' yourfile