LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Use sed to replace a single letter? (https://www.linuxquestions.org/questions/linux-newbie-8/use-sed-to-replace-a-single-letter-4175486459/)

Spazztic_Killer 12-01-2013 11:59 AM

Use sed to replace a single letter?
 
I cant seem to get sed to replace a single letter, when i use
Code:

sed -e 's/J/M/g'
It ends up matching more than a single letter of the data and replaces it to.

The data looks like

lastname:firstname:middlename
Quote:

Smith:James:J
it will look like

Quote:

Smith:Mames:M
Not sure how to confine sed to a single letter match?

druuna 12-01-2013 12:18 PM

The g makes it global (for all instances in the line). If you remove the g then only the first instance will be changed:
Code:

sed 's/J/M/'
You can change the second occurrence like this:
Code:

sed 's/J/M/2'
If the letter is the last on a line:
Code:

sed 's/J$/M/'
- Sed - An Introduction and Tutorial
- sed, a stream editor

Shadow_7 12-01-2013 12:46 PM

^ as above. The /g makes it do it multiple times for every instance in a line. Drop the g and it does the first instance only.

Madhu Desai 12-01-2013 11:45 PM

Quote:

Originally Posted by Spazztic_Killer (Post 5073460)
Not sure how to confine sed to a single letter match?

You can use word boundary (\< \> ot \b) to achieve it.

Code:

sed 's/\<J\>/M/g'
sed 's/\bJ\b/M/g'



All times are GMT -5. The time now is 10:04 AM.