Vim delete starting from character to end of line
Mia Lopez
I'm trying to come up with something that will delete all text to end of line from a given character onwards.
E.g. in the example below I want to keep only the IP address:
192.168.2.121/32 -m comment --comment "blah blah bye bye" -j DROP
10.1.3.207 -m comment --comment "much longer comment with all kinds of stuff" -j DROP
172.16.1.0/24 -m comment --comment "Drop this range" -j DROPThe pattern to remove from is -m, i.e., reading from left, the first "-" encountered. From that "-" to end-of-line should be deleted on every line in the file.
I'm stumped on this one, guidance would be appreciated.
6 Answers
A global command would be a good fit
:g/-/norm nDExplanation
:g : Start a Global Command (:h :g for extra help on global commands)
/- : Search for -
/norm nD : Execute nD in Normal Mode where n - jumps to the match D - delete to the end of the line 4 There's a simple method to do that under the normal mode:
/-mto let the cursor move to the first occurrence "-m" in the file.- Press
d$to delete characters from the cursor to the end of the line. - Press
nto find another "-m". - Press
.to redo step 2.
Isn't this as simple as:
:%s/-m.*//?
Or I didn't understand the problem right?
3I would do:
:%norm f D"On each line, move the cursor to the first space and cut everything from the cursor to the end of the line."
:help range
:help :normal
:help f
:help D I would register a macro, for example:
- Put the cursor on the first line, at position
0 qlstart registering a macro on the letterlt-D+qend the macro- Launch the macro as many times as you want eg:
3@lto launch it three times
Explanation of t-D+:
t-goes in front of the next occurence of-Ddelete till end+, jumps to the next line at the beginning of the string so that we can chain macros (lshould work too on vim as you deleted till the end)
As @Nobe4 stated you can also register the macro on one line (eg qlt-Dq) and then repeat on a visual selection: VG:normal!@l.
Select your text with visual mode and then use:
:'<,'>s/\([^- ]*\).*/\1/Decomposition:
:'<,'>s/ " start a substitution on current selected lines
\([^- ]*\) " capture a groupe of everything except a space and a -
.*/ " match the rest of the line
\1/ " replace by only the matched group