In my yaml file , i want to delete a block using Sed After matching a pattern .
Example:
Keypages:
- name: Key pages
LaunchPad:
- name: "\U0001F680Launch Pad"
- location: US
Microservices:
- name: 'Micro services '
In this example , when matching LaunchPad(for example) in the start of a line, i want to delete it ans its block ( for me the lines starting with - and then stop when not finding -)
Result :
Keypages:
- name: Key pages
Microservices:
- name: 'Micro services '
thank you
CodePudding user response:
Use this Perl one-liner:
perl -i.bak -ne 'print unless m{^LaunchPad} .. !m{^\s*-}' in_file
The Perl one-liner uses these command line flags:
-e
: Tells Perl to look for code in-line, instead of in a file.
-n
: Loop over the input one line at a time, assigning it to $_
by default.
-i.bak
: Edit input files in-place (overwrite the input file). Before overwriting, save a backup copy of the original file by appending to its name the extension .bak
.
EXPR1 .. EXPR2
: this is true in between where expression EXPR1 is true and expression EXPR2
is true, inclusive.
!m{^\s*-}
: not matching a pattern where the line starts with 0 or more whitespace characters followed by a dash.
SEE ALSO:
perldoc perlrun
: how to execute the Perl interpreter: command line switches
perldoc perlre
: Perl regular expressions (regexes)
perldoc perlre
: Perl regular expressions (regexes): Quantifiers; Character Classes and other Special Escapes; Assertions; Capture groups
perldoc perlrequick
: Perl regular expressions quick start
CodePudding user response:
Using the python PyYaml library, you can use the following script as a filter that removes any section named LaunchPad
:
import sys, yaml
data = yaml.safe_load(sys.stdin)
del data['LaunchPad']
yaml.dump(data, sys.stdout)
Simply run: python above-script < input.yml > output.yml
Given this input:
Keypages:
- name: Key pages
LaunchPad:
- name: "\U0001F680Launch Pad"
- location: US
Microservices:
- name: 'Micro services '
The above script produces this output:
Keypages:
- {name: Key pages}
Microservices:
- {name: 'Micro services '}
CodePudding user response:
Using sed
$ sed '/^LaunchPad/,/^[[:alpha:]]/{/^LaunchPad/!{/^-/d};/^LaunchPad/d}' input_file
Keypages:
- name: Key pages
Microservices:
- name: 'Micro services '
/^LaunchPad/,/^[[:alpha:]]/
- Match lines beginning withLaunchPad
to the next line beginning with any alphabetical character/^LaunchPad/!
- Ignore lines beginning withLaunchPad
/^-/d
- Match lines beginning with a dash then delete them/^LaunchPad/
- Finally, delete the line beginning withLaunchPad
CodePudding user response:
This might work for you (GNU sed):
sed -n '/^LaunchPad:/{:a;n;/^-/ba};p' file
Turn off implicit printing -n
.
Match a line beginning LaunchPad:
and then fetch following lines beginning with -
.
Print all other lines.
Alternative:
sed '/LaunchPad:/{:a;N;/^-/Ms/\n//;ta;D}' file