0

In below XML snipped, I need to delete the unwanted lines matching an artifact ID value:

    <groupID>com.test</groupID>
    <artifactID>nginx-node</artifactID>
    <verion>1.0</version>
    <groupID>com.test</groupID>
    <artifactID>nginx-node</artifactID>
    <verion>1.1</version>
    <groupID>com.test</groupID>
    <artifactID>nginx</artifactID>
    <verion>1.2</version>

I need to delete all XML lines current, before and after by matching the value of artifact ID ie "nginx-node" in an above XML file

command tried:

grep -iv "nginx-node" file.

Actual output:

 <groupID>com.test</groupID>
    <verion>1.0</version>
    <groupID>com.test</groupID>
    <verion>1.1</version>
    <groupID>com.test</groupID>
    <artifactID>nginx</artifactID>
    <verion>1.2</version
    **Expected output:**
    <groupID>com.test</groupID>
    <artifactID>nginx</artifactID>
    <verion>1.2</version>
wp78de
  • 18,207
  • 7
  • 43
  • 71
  • Why don't you use an additional tool like [xpath](https://stackoverflow.com/questions/15461737/how-to-execute-xpath-one-liners-from-shell) – JGK Sep 16 '18 at 10:00

1 Answers1

0

This requires a multi-line search and replace operation, e.g. using Perl. Indeed, a one-liner gets the job done:

perl -i -0pe "s/^\s*\S*\s*<artifactID>nginx-node<\/artifactID>\s*\S*\s*$//gm" input.txt

Online Regex Demo (see regex explanation on the right hand)

Explanation of the flags:

  • -i tells Perl to perform an in-place replacement, i.e. updates the input file immediately. (Omit this option for a dry-run)
  • -0 turns Perl into "file slurp" mode, i.e. the entire input file is read in at one instead of line by line. This enables multi-line search and replace.
  • -pe enables to run Perl code directly, in our case pattern matching and replacement.

If you want to find and replace in more than one files, you couple it with find and xargs, e.g.

find ~/mystuff -name "*.txt" | xargs perl -i -0pe 's/regex/replacement/g'
wp78de
  • 18,207
  • 7
  • 43
  • 71