8

I need to replace a set of known words with sed, but I must keep case-sensitivity of original words. For example, "Abc" is replaced with "Def", but "abc" is replaced with "def". Only the first letter of the word can vary in case (so no aBC or abC words are allowed).

I know how to do this using 2 regexps per word, but is it possible to do it using only 1 regexp per word?

2
  • 1
    Please show your two regexes. Commented Mar 5, 2011 at 19:54
  • 2 sed commands for 1 word: s/abc/def/g s/Abc/Def/g It is not a problem for one word, but I have over 1000 of them... Commented Mar 5, 2011 at 20:04

2 Answers 2

6

You can script the creation of the sed script. Assuming a file of word pairs:

$ cat words.dat
apple pecan
banana walnut
cherry almond

and a text file:

$ cat textfile.txt
apple
banana
cherry
I would like an apple pie. Cherry pies are good, too. What about bananas?
Bananas are full of potassium.

You can do:

awk '{print "s/" tolower($1) "/" tolower($2) "/g;s/" toupper(substr($1,1,1)) tolower(substr($1,2)) "/" toupper(substr($2,1,1)) tolower(substr($2,2)) "/g"}' words.dat > sedscript.sed

The sed script:

$ cat sedscript.sed
s/apple/pecan/g;s/Apple/Pecan/g
s/banana/walnut/g;s/Banana/Walnut/g
s/cherry/almond/g;s/Cherry/Almond/g

and then:

$ sed -f sedscript.sed textfile.txt
pecan
walnut
almond
I would like an pecan pie. Almond pies are good, too. What about walnuts?
Walnuts are full of potassium.
2
  • Excellent, this is exactely what I need. Thank you very much Dennis! Commented Mar 5, 2011 at 20:42
  • This is brilliant, thanks. In my case I did the following: ``` sed -e 's/resender/ui/g;s/Resender/Ui/g' pom.xml ```
    – Pedro
    Commented Oct 9, 2012 at 0:50
1

If you're using a list of >1000 (abc->def, ghi->jkl,...), why not turn it into a list of >2000 (abc->def, Abc->Def, ghi->jkl, Ghi->Jkl,...) in one step, (using sed 'y' or some other tool) and use that?

1

Your Answer

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

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