I have linux machine red-hat 5.1

how to replace only the right single char (most side of string)

example from my sed syntax (not good because its replaced both "a" chars) l

 echo machine1a | sed s'/a/b/g'


But the requested answer should be - machine1b and not mbchine1b

  • requested answer is the same as a task ?? if echo machine1a | sed s'/a/b/' SHOULD return the same string then I dont know why are you trying to sed it...just echo it. Unless you meant to say machine1b ? – milosgajdos May 14 '12 at 22:45
  • see my update - you right I forget the "g" in the sed – Eytan May 14 '12 at 22:50
  • 1
    are you trying to replace the last a with b? or are you trying to replace whatever the last character is? – stew May 14 '12 at 23:29
  • why not use another tool than 'awk'. Here is the same functionality 'tcl: #!/usr/bin/tclsh set nameA "MachineA"; set nameB "[string range $nameA 0 end-1]B"; puts "$nameA\t$nameB" ' – Cesar A. Rivas May 15 '12 at 1:39

You can use the end-of-pattern-space pattern. The pattern $ matches the null string at the end of the pattern space. With this pattern you can avoid using rev as advised above.

  $ echo machine1a | sed 's/a$/b/'
  • This is what you should use. I don't think you need the '-e' though. – opsguy May 15 '12 at 1:55
  • @opsguy Thank you. -e is not necessary unless several scripts are supplied on the command line. Fixed. – Dmitri Chubarov May 15 '12 at 3:07
% echo machine1a | rev | sed s'/a/b/' | rev

I can't find a way to do this with sed alone. There is a flag to the s operation specifies to only replace the Nth match, but counting from the end doesn't work.

% echo machine1a | sed s'/a/b/2'
  • I dont have the rev command – Eytan May 14 '12 at 23:00
  • awesome solution! :) @Eytan, read below my generic bash answer. – milosgajdos May 14 '12 at 23:06

this is not possible using one simple sed expression. Instead do something like this ie. use bash's string manipulation capabilities:

var=machine1a; echo "${var%?}b"

But if you REALLY need sed then you can run the following command:

echo machine1a | sed s'/\(.*\)\(.\)$/\1b/g'

Sorry for confusion above by saying that it was not possible. I normally do this kind of stuff in bash using bash's string handling capabilities.

  • I do not think it is not possible. In sed you can use the $ pattern that matches the end of the pattern space. – Dmitri Chubarov May 14 '12 at 23:33
  • you are right...I dont know what was I thinking...probably because I normally do this kind of string operations using bash capabilities – milosgajdos May 15 '12 at 8:09

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.