Search code examples
bashunixscriptingsedend-of-line

sed filter to substitute '!' for periods and '!!' for periods at the end of lines


I want to write a sed filter that changes all periods in its input to exclamation marks, unless the period is at the end of a line, in which case the period is replaced with 2 exclamation marks (ie. !!).

So far, this is what I have:

sed -e 's/\./\!/g' -e 's/\!\n/\!\!\n/g' input_exp

where input_exp is a file that has a few sentences written in it. The command does not work though. Is '\n' not the correct end of line character in unix/bash? Do I need an extra '\' before '\n'?

Thanks for your help.


Solution

  • sed -e 's_\.$_!!_g' -e 's_\._!_g' input_exp
    

    I've used _ instead of / for a slightly higher degree of readibility. You can also use

    sed -e 's/\.$/!!/g' -e 's/\./!/g' input_exp
    

    if you want to, of course. \n stands for newline, and is not the same as end of line.