4

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 ?

8

One way to do this is as follows:

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

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

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

Result:

%> 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
  • 2
    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
0

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.

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.