Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to write a sed expression to detect lines similar to this:

s0:12345:respawn:/sbin/agetty -8 -s 115200 ttyS0 linux

and replace the ttys0 with something_else

I do not want to detect commented out lines (beginning with #)

I can replace the whole line, but how to I just replace the substring, leaving the rest of the line intact ?

share|improve this question
up vote 8 down vote accepted

One way to do this is as follows:

echo 's0:12345:respawn:/sbin/agetty -8 -s 115200 ttyS0 linux' | 
    sed -e '/^[^#]/ s/ttyS0/foo/'
share|improve this answer

Match the part before ttyS0 and those after ttyS0, also check if line doesn't begin with #:

sed 's/^[^#]\(.*\)ttyS0\(.*\)/\1something\2/'


%> echo "s0:12345:respawn:/sbin/agetty -8 -s 115200 ttyS0 linux" | sed 's/^[^#]\(.*\)ttyS0\(.*\)/\1something\2/'
0:12345:respawn:/sbin/agetty -8 -s 115200 something linux
share|improve this answer
You don't need last group and \2 at all. Also if it is possible it's much better do not use backreference cause usually it eats too many resources. – rush Sep 11 '12 at 15:35

If it always starts with s[number]colon you could do (with GNU sed):

sed -r '/^s[0-9]+:/s/ttyS0/something_else/' infile

Which changes any line that starts with the regex, adapt to suit your needs.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.