5

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' mbchine1b 

But the requested answer should be - machine1b and not mbchine1b

4
  • 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 ? Commented May 14, 2012 at 22:45
  • see my update - you right I forget the "g" in the sed Commented May 14, 2012 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? Commented May 14, 2012 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" ' Commented May 15, 2012 at 1:39

3 Answers 3

8

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/' machine1b 
2
  • This is what you should use. I don't think you need the '-e' though. Commented May 15, 2012 at 1:55
  • @opsguy Thank you. -e is not necessary unless several scripts are supplied on the command line. Fixed. Commented May 15, 2012 at 3:07
2
% echo machine1a | rev | sed s'/a/b/' | rev machine1b 

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' machine1b 
2
  • I dont have the rev command Commented May 14, 2012 at 23:00
  • awesome solution! :) @Eytan, read below my generic bash answer. Commented May 14, 2012 at 23:06
1

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.

2
  • I do not think it is not possible. In sed you can use the $ pattern that matches the end of the pattern space. Commented May 14, 2012 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 Commented May 15, 2012 at 8:09

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.