I’m not sure if this can be accomplished with regex, so here goes and hoping for the best.
If in vim I do,
:g/function
I get a list of all function rows.
Now, I’d like that but with comments (!) below until the first non comment row, so I get something like:
3 function MyFunction()
4 !This is a comment
5 !This is also a comment
23 function MyOtherFunction()
24 !This is a comment
25 !This is also a comment
Something like that possible ?
Yes
Update
An explanation was suggested…so here goes… vi(1) is powerful in part because it is a cursor-addressing extension to Ken Thompson’s original line-oriented ed(1) editor. (ed(1) and its spinoff
exis still available on Linux after all these years, albeit in clone form like vi itself.) ed and its early-unix siblings were the first programs anywhere to use regular expressions.Ok, create a file with 26 or so lines, one for each letter of your alphabet and start vi, ed, or ex. (For ed or ex, leave out the : characters.) Try:
The general form of a vi command is: addr, addr2 commmand
In my example the command is just
pfor print. addr1 and addr2 are usually a line number or a regular expression using /re/ to search downward or ?re? to search upward. Try/c/;/g/pwhich prompts me to explain: the;causes the editor to switch to the line found by the first address before it evaluates the second address. It doesn’t always matter in the default wrapscan mode but if you type:set nows(not in ed) then search patterns won’t wrap and the difference between,and;becomes bigger.The most important line mode command wasn’t used in my example but it should be mentioned here:
:s/pattern/replacement/or:s/pattern/replacement/g. This command can of course take addresses so a typical command is1,$s/old/new/gThe$identifies the last line. The default address for most commands is the current line but for theglobalorgcommand it defaults to1,$and has the general formFor example, say I’m Jeff but I want to blame Joel for different types of critical errors in the logs. I need to be stealthy and not change the Jeff’s on mere warning lines, so I need:
That will run the substitute command on every line of the file that has the pattern “critical anything error” and then just change Jeff to Joel.
So now the answer should be fairly clear. The command works as follows: on every line of the file, check to see if the line begins with /^func/ (func at the beginning of the line) and if it does, start with
.(the current line) then, resetting the current address to that line (;) search for a line that does NOT begin with!, and if it’s found, subtract one from the line number found (back up slightly to the last actual comment) and then just run theprintcommand.