Hacker News new | ask | show | jobs
by beachstartup 3404 days ago
in your editor, without leaving the keyboard, how would you search-and-replace using a 2-variable regex, only between lines 275 and 1305, and then turn every instance of 'TEST_' into a lowercase, but only on the lines that didn't match?
3 comments

How often do you find yourself doing operations like this? I feel like it would take me more time to formulate and confirm that your set of commands are correct than it would for me to just ctrl+f to each instance and then ctrl-v the ones that needed to be changed. Don't get me wrong, I think it is really cool that you can do this, but it feels like this requires a level of fu that is beyond most typical programmers.
you search and replace by hand?

... are you serious?

Thanks for the substantive reply;)

In almost all cases where I need to do a find/replace there are typically no more than 4-5 references that need to be updated. And I think a better way to phrase my behavior is I search, inspect the code to make sure that my change won't introduce a bug or some unintended consequence, and then replace. This may be slower, but in the grand scheme of things it barely registers on my overall productivity and if it saves even one bug from getting introduced into the code than the extra time spent probably pays for itself. If I need to update more than just a handful of references, than Sublime has a perfectly functional find/replace tool, but I have only ever really needed it maybe 3-4 times in the last few years.

To get back to the question at hand. How long does it take you to formulate these series of commands in your example? Because to me it feels like it would take longer to come up with a correct set of commands for your example than it would be to just search and replace 'by hand'. Of course if you are updating 100's of references than spending some extra time to formulate your solution makes sense, but in your example, you limited your search ~1000 loc, so presumably you are only updating a few lines, maybe a dozen at most? I understand that vim is powerful tool, but it seems to solve problems that I don't have (or that I don't consider to be problems), and I am genuinely curious as to the sort of problems and types of code bases that vim aficionados work on.

In vim, it would probably have to be done in two separate commands

    # Search and replace using a 2-variable regex
    :275,1305s/two_variable_regex/first\1second\2/g

    # Replace TEST_ with test_
    :275,1305g!/a_regex/s/TEST_/test_/g
But, if it's too convoluted to do something like this in vim, you can instead do something like:

    :275,1305 !perl -ne '# substitution, then print'
I would do this in awk. I could specify the line numbers. Or I could use the editor option to pass selection through said awk script. Or I could pipe xclip to and from the script.

Someone else could do it with sed, but I prefer awk.