Can a long sed command be broken over several line

2019-04-05 09:03发布

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

6条回答
该账号已被封号
2楼-- · 2019-04-05 09:41

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"
查看更多
爷的心禁止访问
3楼-- · 2019-04-05 09:46
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
查看更多
闹够了就滚
4楼-- · 2019-04-05 09:59

Yes it can, just quote it as usual:

sed 's/foo/bar/g
     s/baz/quux/g'
查看更多
爷、活的狠高调
5楼-- · 2019-04-05 10:01

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
查看更多
Summer. ? 凉城
6楼-- · 2019-04-05 10:02

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.

查看更多
相关推荐>>
7楼-- · 2019-04-05 10:05

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

查看更多
登录 后发表回答