0

I have a file in the following format:

--- V1 ---
Hi there
--- V2 ---
--- V3 ---
What's good
--- V4 ---
--- V5 ---
--- V6 ---

I want to use some kind of bash script to remove any of the lines beginning with three dashes that are not immediately followed by a line that does NOT have three dashes, e.g.:

--- V1 ---
Hi there
--- V3 ---
What's good

I can easily remove ALL of the lines beginning with dashes, but don't know how to do it based on the following line (or alternatively, based on the line preceding the non-dashed lines).

5
  • Probably not an answer to your question, but a 1 line partial solution - grep -v -B1 "^---" file.name will look for all lines which don't start with "---", and display those lines and line line immediately prior to it. This will only work if each payload line is followed and preceded by a line with "---", ie won't work over multiple lines.
    – davidgo
    Commented Feb 18, 2016 at 1:37
  • Does it have to be a bash script? Something like this could be done with sed, grep, awk, or even vim.
    – Karu
    Commented Feb 18, 2016 at 2:44
  • It doesn't have to be a bash script, no. Doesn't using grep not disqualify it from being a bash script, though?
    – Birdie
    Commented Feb 18, 2016 at 4:55
  • @davidgo Your answer actually worked for multiple lines correctly, so if you want to make it an answer then feel free and I'll mark it correct. Otherwise I will accept Gombai Sandor's answer, which is more complex but also correct.
    – Birdie
    Commented Feb 21, 2016 at 22:21
  • Thanks for this. I think Gombai Sandors answer is pretty cool so I upvoted it, but I added mine because I think its a lot easier and more efficient.
    – davidgo
    Commented Feb 21, 2016 at 22:33

2 Answers 2

0
grep -v -B1 "^---" file.name 

Will look for all lines which don't start with "---", and display those lines. "-B1" displays the line immediately prior.

2

I guess "some kind" means that you don't insist on pure bash. If so, then awk can do it well:

/tmp$ input="--- V1 ---
Hi there
--- V2 ---
--- V3 ---
What's good
--- V4 ---
--- V5 ---
--- V6 ---"
/tmp$ echo "$input" | awk '/^---/ {row = $0; if (wasdashed) next; wasdashed=1; next}; { if (wasdashed) print row; print $0}'
--- V1 ---
Hi there
--- V3 ---
What's good
/tmp$

Anyway, with the very same logic, pure bash would be possible, but with much more coding.

2
  • This gives completely different output for me; --- V1 --- is repeated after every line, but is otherwise the same output as input.
    – Birdie
    Commented Feb 19, 2016 at 4:20
  • @Birdie Make sure to drop the leading spaces when copy/pasting the above example. Works fine then.
    – Oldskool
    Commented Feb 19, 2016 at 9:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .