2

I am looking for a Linux command-line utility that can do text replacement (think sed or sd) and is able to automatically extend your search-and-replace pattern to strings that have different word separation methods. By word separation I mean things like hyphens/underscores/spaces between words, camelCase, UpperCamelCase, etc.

So if you told it to replace an example string with another example string, it could, with minimal effort on the user's part (e.g. adding some CLI options), also replace an-example-string with another-example-string, anExampleString with anotherExampleString, and so on.

Keywords for other people searching: case-preserving replace

2
  • Not a CLI command but a bunch of vim plugins can be found in the replies to this question: vim-abolish and keepcase.vim
    – smheidrich
    Dec 18, 2022 at 13:55
  • FYI, I know you asked for an existing program/tool, but I thought you might like to know this: Python regular expressions allow for functions/methods to be run on matches for replacements, which could allow for changing the case in the desired fashion. You can even configure Nano to have a keyboard shortcut launch such a Python script to do such replacements in Nano. Regular expressions in and of themselves will do most of what you want, but for the casing, you might need to pass in functions for the replacement. Jan 10 at 3:04

2 Answers 2

1

sed is able to do this if you give it a suitable pattern.

sed -i 's/\(an\)\([^a-zA-Z]?\)\(example\)\([^a-zA-Z]?\)\(string\)/another\2\3\4\5\6/'

Obviously I have gone overboard with the grouping, for this example you could use

sed -i 's/an\([^a-zA-Z]?example[^a-zA-Z]?string/another\1/'

The point is that you can break up input into the "words" and the "word separators" and then put them back together. The interesting question is can we write a program to write the sed script for you, to which I believe the answer is "no".

What is not obvious is how you would want to map say "a black sheep" into "the red and yellow cow". I might guess that you want "a" -> "the", "black" -> "red and yellow" and "sheep" -> "cow" based on nouns and adjectives, but this doesn't help "ACamelShip" -> "Xyzzy in motion".

TL;DR

sed can do what you want, but I can't give you an automatic tool for correctly doing what you want automatically as the problem is under-specified.

0

As so often, I ended up writing my own draft of what I had in mind: https://gitlab.com/smheidrich/cawspr

Please feel free to open issues about missing functionality or bugs and to submit merge requests.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.