Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I am trying to write a sed expression to detect lines similer 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
add comment

3 Answers

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
add comment

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
share|improve this answer
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
add comment

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
add comment

Your Answer

 
discard

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.