1

I have some files that look like this:

0
04
040
040t
040te
040tes
040test
040test2
041
041t
041te
041tes
041test
041test1
0n
0ne
0ne-
0ne-o
0ne-os
0ne-osx

I need to delete all the lines that are included in the line after them. IOW, I need to reduce it to this:

040test2
041test1
0ne-osx

Any suggestions for the Linux CLI or vim to accomplish this? Thanks.

2

In Vim you could try this global command:

g/^\(.*\)\n\1.\+/d
│ ├────────────┘ │
│ │              └ delete the matching lines (see `:h :d`)
│ │
│ └ pattern matching 2 lines, the second one starting like the 1st
│
└ global command (see `:h :g`)
| improve this answer | |
1

Perl to the rescue!

perl -lne 'print $prev if -1 == index $_, $prev;
           $prev = $_;
           END { print $prev }' -- file.txt
  • -n reads the input line by line
  • -l removes newlines from input and adds them to print
  • $_ is the special variable that contains the actual line read from the input
  • index returns -1 if the substring (2nd argument) isn't found in the string (1st argument)
  • the END block is needed to print the last line of the file
| improve this answer | |
  • Thanks for the post. I assume that this works, but as I explicitly called out Vim, I'm going to mark the other response as the answer. – Brannon Sep 18 '18 at 21:26

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.