7

I want to replace quotes that are at the start of a word.

For example:

$ echo "a 'line' a single ' after a  'keyword' with a few space's for a program"\
| sed "s/\b'/X/g"
a 'lineX a single ' after a  'keywordX with a few spaceXs for a program

but as you can see they are getting replaced at the end of words not the beginning.
How to replace ones that start a word?

9

This replaces ' at word beginnings:

$ echo "a 'line' a single ' after a  'keyword' with a few space's for a program"| sed "s/'\b/X/g"
a Xline' a single ' after a  Xkeyword' with a few spaceXs for a program

For humans, not computers, there is one peculiarity here: the computer counts space's as two words and replaces the ' because it is at the beginning of the second word.

Discussion

\b marks a word boundary, either beginning or end. Now consider \b'. This matches a word boundary followed by a '. Since ' is not a word character, this means that the end of word must precede the ' to match. To use \b to match at beginnings of words, reverse the order: '\b. Again, since ' is not a word character, this will only match if a word follows the '.

Some seds, like GNU sed, support \< to match the beginning of words. This doesn't help in your case because ' is already not a word character and that forces the issue.

What to do about "space's"

If you don't want the ' replaced in space's because the ' appears at the end of a word, you can reverse the logic by using \B:

$ echo "a 'line' a single ' after a  'keyword' with a few space's for a program"| sed "s/\B'/X/g"
a Xline' a single X after a  Xkeyword' with a few space's for a program

\B matches at not a word boundary. Thus \B' matches at ' (space-quote) because neither space nor quote are word characters. It does not match at space' because e' is a word boundary: e is a word character and ' isn't.

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.