Wednesday, January 31, 2024

[SOLVED] replace line contents having / using sed

Issue

Script looks as below

[Unit]
Description=Serial Getty on %I
Documentation=man:agetty(8) man:systemd-getty-generator(8)

Type=idle
Restart=always
UtmpIdentifier=%I
ExecStart=-/sbin/agetty -o '-p -- \\u' --keep-baud 115200,38400,9600 %I $TERM

Want to replace

ExecStart=-/sbin/agetty -o '-p -- \\u' --keep-baud 115200,38400,9600 %I $TERM
with 
ExecStart=-/sbin/agetty 9600 %I $TERM

Tried with these commands

sed -i 's/ExecStart=-/sbin/agetty -o '-p -- \\u' --keep-baud 110200,38900,9680 %I $TERM/ExecStart=-/sbin/agetty 9600 %I $TERM/g' 

but it is not working due to presence of / in search string

Can anyone please help


Solution

replace line contents having / using sed

[...]

it is not working due to presence of / in search string

That's one of the reasons it's not working. Your example also has a problem related to there being quotes embedded in the target text.

With respect to the / characters, there are several possibilities. The easiest one that serves the general case is to use a different character for the pattern delimiter. / is most conventional for that purpose, but you can choose any character. The ,, |, and # are fairly common alternatives. For example:

sed -i "s#ExecStart=-/sbin/agetty -o '-p -- \\\\u' --keep-baud 110200,38900,9680 %I \$TERM#ExecStart=-/sbin/agetty 9600 %I \$TERM#" myunit.service

(Note: I removed the g option because it's moot: the pattern will not match more than once per line anyway.)

But that's a bit heavy-handed. Your input has only one ExecStart line, so that's sufficient to identify the line to edit, and you don't need to replace the whole line. I might instead use something like this:

sed -i '/ExecStart/ s/agetty.*/agetty 9600 %I $TERM/' myunit.service

That says: on each line matching pattern /ExecStart/, replace the longest substring starting with agetty with the string agetty 9600 %I $TERM. That's crafted for your specific example, of course, but similar can be used on many other cases.



Answered By - John Bollinger
Answer Checked By - Pedro (WPSolving Volunteer)