Wednesday, October 29, 2008

Sed Trick

My friend is asking me ...
I need to run a sed command to change "CONSOLE=/dev/console" to "#CONSOLE=/dev/console". But the back slashes are giving me problems.

In Solaris, you can allow root direct access by commenting out 'CONSOLE=/dev/console' in the /etc/default/login file.

If you were to use sed 's/.../.../' like below, you will need to escape the forward slash sequence with '\/' to input the forward slash

sed 's/CONSOLE=\/dev\/console/#CONSOLE=\/dev\/console/' /etc/default/login

The above is definitely very clumsy. Do you know that there is a trick in sed that allows you to use another character (any character you provide to sed) for the 'pattern separator'. In my case I used "!" because "!" does not appear in the sed expression and therefore I do not have to use any backslashes.

sed 's!CONSOLE=/dev/console!#CONSOLE=/dev/console!' /etc/default/login

You can even shorten the sed command by asking it to remember your pattern so that you can reuse it again. Anything with brackets (but you need to escape them) will be remembered and you can refer to it as \1 for the first pattern, \2 for the second, etc.

sed 's!\(CONSOLE=/dev/console\)!#\1!' /etc/default/login



Post a Comment

<< Home