1

I have a file in which I want to change all of the code that has the following format : n{,3}L{,2}n{,5} where n= [0-9] any number and L [a-zA-Z] any letter either capital or not

I want to change A or a into AB and d or D into DK, something like this:

 Annnnn--> ABnnnnn ; Dnnn-->DKnnn 

the file looks like:

$ cat filename
123a67,64,xx
A67990,12,ttt
89d7,34,ggg
234AB445,78,ooo
145aB7699,67,rrr
278Dk89,25,ppp

I tried the following sed script

sed 's/[aA]/AB/g;s/[dD]/DK/g' filename

it works for instances which have only A or D but for those which are already AB or DK it adds up the letter as AB--> ABB or DK-->DKK. Any help appreciated with explanation. Thanks!

3

As for what's wrong with your script, you are replacing A or a with AB and D or d with DK, so any pre-existing B or K would not be affected; sed is not looking for it. You could put an optional [bB] or [kK] using ? (zero or one of the preceding character) to make it replace that character too if it occurs.

To make sure the replacement only happens if [aA] or [aA][bB] etc is followed by a number, you can add the number to the pattern and add it back in the replacement with () and \1

sed -r 's/ab?([0-9])/AB\1/Ig;s/dk?([0-9])/DK\1/Ig' filename

I am using -r to use ERE (so no need to escape ?) and I for case-insensitive search instead of using character classes.

  • @Daniel it's a pleasure :D – Zanna Dec 1 '16 at 22:21
  • a Question! I just realized that your script would not successful if there would be another letter already in the filename. for instance it will also change the nnAYnnn--> nnABYnnn which I do not want to see such change and want to keep this intact and observe only changes for code has only "A" or "AB". Do you have any idea about it? – Daniel Dec 1 '16 at 22:35
  • @Daniel ah so, if we have [Aa], change it to [AB] only if the next character after [Aa] is [0-9], or [bB] and then [0-9]? – Zanna Dec 1 '16 at 22:42
  • Yes, Exactly! :) – Daniel Dec 1 '16 at 22:45
  • @Daniel I've edited, I think I understood correctly, please comment if not :) – Zanna Dec 1 '16 at 22:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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