Home » Linux » Can a long sed command be broken over several lines?

Can a long sed command be broken over several lines?

Posted by: admin January 30, 2018 Leave a comment

Questions:

I have sed command that is very long

sed -i 's/append ro initrd=initrd.img quiet splash nbdport=2000/append ro initrd=initrd.img quiet splash nbdport=2000 video=LVDS-1:d/g' /var/lib/tftpboot/ltsp/i386/pxelinux.cfg/default

Can it be broken over several lines to make it more clear what it does?

E.g. something like?

sed -i 's/
append ro initrd=initrd.img quiet splash nbdport=2000
/
append ro initrd=initrd.img quiet splash nbdport=2000 video=LVDS-1:d
/g'
/var/lib/tftpboot/ltsp/i386/pxelinux.cfg/default
Answers:

A couple of ways you can make this smaller. If you are just appending the text to the end of the line, you can use sed like this:

sed -i '/append ro initrd=initrd.img quiet splash nbdport=2000/s/$/ video=LVDS-1:d' ...

Otherwise, use shell variables to split it up a bit.

PXE_BOOT_FILE=/var/lib/tftpboot/ltsp/i386/pxelinux.cfg/default
SEARCH_PATTERN='append ro initrd=initrd.img quiet splash nbdport=2000'
REPLACE_PATTERN="$SEARCH_PATTERN video=LVDS-1:d"
sed -i "s/$SEARCH_PATTERN/$REPLACE_PATTERN/g" "$PXE_BOOT_FILE"

Questions:
Answers:
sed 's/[long1][long2]/[long3][long4]/' file.txt

you can use the usual backslash for spreading the expression on multiple lines. It is important though that the lines following a backslash do not feature a space at the beginning.

sed 's'/\
'[long1]'\
'[long2]'\
'/'\
'[long3]'\
'[long4]'\
'/' file.txt

Questions:
Answers:

This might work for you:

sed -i 's/append ro initrd=initrd.img quiet splash nbdport=2000/& video=LVDS-1:d/g' /var/lib/tftpboot/ltsp/i386/pxelinux.cfg/default

or

string="append ro initrd=initrd.img quiet splash nbdport=2000"
sed -i 's/'"$string"'/& video=LVDS-1:d/g' /var/lib/tftpboot/ltsp/i386/pxelinux.cfg/default

N.B. the & in the Right Hand Side of the substitution represents all of the matching regex on the Left Hand Side

Questions:
Answers:

Regex isn’t meant to use such long expression, why not shortcut the needle like this:

sed -i 's/nbdport=2000/nbdport=2000 video=LVDS-1:d/g' /var/lib/tftpboot/ltsp/i386/pxelinux.cfg/default

Questions:
Answers:

Yes it can, just quote it as usual:

sed 's/foo/bar/g
     s/baz/quux/g'

Questions:
Answers:

Sandra, you can alternatively put that large sed command in a file, say tftp.sed and invoke sed like sed -i -f tftp.sed /var/lib/tftpboot/ltsp/i386/pxelinux.cfg/default where tftp.sed file looks like:

# my very long line:
s/append ro initrd=initrd.img quiet splash nbdport=2000/append ro initrd=initrd.img quiet splash nbdport=2000 video=LVDS-1:d/g
# note: every sed command in this file must be in a separate line

As you can see above, you can have multiple sed commands inside the sed source file, just be sure they are each in a separate line.