My file contains the below entries:

cat /tmp/test.yaml
    hash: e6df90d38fa86f0e289f73d79cd2cfd2a29954eb

    hash: e6df90d38fa86f0e289f73d79cd2cfd2a29954eb
    hash: 1746f03d57491b27158b0d3a48fca8b5fa85c0c2

    hash: 1746f03d57491b27158b0d3a48fca8b5fa85c0c2

and so on...

I wish to delete a particular IP say and it's file details from test.yaml

They below regex helps grab the details i wish to delete from the file and therefore i store it in a variable called check:

export check=`grep -Pzo '[^#](^|\n)*^(?!( |\n))' /tmp/test.yaml`

echo $check /tmp/win5835113081224811756.jar: hash: e6df90d38fa86f0e289f73d79cd2cfd2a29954eb /tmp/win03745991442278706.jar: hash: e6df90d38fa86f0e289f73d79cd2cfd2a29954eb

I then wanted to use the variable check to remove the grabbed entries from the file.

I tried the below commands but they do not help.

grep -v "$check" /tmp/test.yaml


sed "/${check}/d" /tmp/test.yaml sed: -e expression #1, char 1:
 unterminated address regex

Can you please suggest how can i fulfill my requirement?

  • You can't grep across multiple lines.
    – RudiC
    Jan 28 '20 at 14:55
  • A more fundamental question is whether there are tools specifically for manipulating YAML files. unix.stackexchange.com/q/550283/5132
    – JdeBP
    Jan 28 '20 at 19:52
  • Why not rephrase the title to "How to remove multiple lines after a match from a text file?"
    – U. Windl
    Jan 28 '20 at 21:31

How far would

awk -v"DEL=" '/^[0-9]/ {LP = 1} $0 ~ "^" DEL {LP = 0} LP' file

get you?


awk -v"DEL=" '/^[^ ]/ {LP = 1} $0 ~ "^" DEL {LP = 0} LP' file

"if the IP addresses are changed to hostnames." (from your comment). Would have helped to include that in the original question.

  • You'll avoid potential "trouble" from the Low-Quality-Review queue reviewers if you phrase your answers in the form of an Answer and not in the form of a Question :)
    – Jeff Schaller
    Jan 28 '20 at 15:30
  • I guess the awk solution will fail if the IP addresses are changed to hostnames.
    – Ashar
    Jan 28 '20 at 15:37
  • Guess the condition to remove text should be the line starting with the given IP upto the line that has white spaces in the start of the line.
    – Ashar
    Jan 28 '20 at 18:49
  • Also be aware that the dots in an IP address have to be escaped when matching regular expressions.
    – U. Windl
    Jan 28 '20 at 21:20
  • @Rudic your solution works like a champ as i tried several permutations and combinations with both IP addresses and hostnames. I however, like a non-awk solution as awk errors when the input file has too lengthy content.
    – Ashar
    Jan 29 '20 at 4:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.