Sed:在一个sed调用中匹配,删除和替换

时间:2014-10-12 17:18:05

标签: arrays bash sed split

假设我有一个字符串:

Image.Resolution=1024x768,800x600,640x480,480x360,320x240,240x180,160x120,1280x720

我想使用sed删除第一部分(Image.Resolution=),然后用逗号分隔其余部分,这样我就可以将所有分辨率放在一个bash数组中。

我知道如何分两步完成(两个sed调用),例如:

sed 's/Image.Resolution=//g' | sed 's/,/ /g'

但作为一项练习,我想知道是否有办法一次性完成。

提前谢谢。

4 个答案:

答案 0 :(得分:1)

只需将;放在命令之间:

sed 's/Image.Resolution=//g; s/,/ /g'

来自info sed

3 `sed' Programs
****************

A `sed' program consists of one or more `sed' commands, passed in by
one or more of the `-e', `-f', `--expression', and `--file' options, or
the first non-option argument if zero of these options are used.  This
document will refer to "the" `sed' script; this is understood to mean
the in-order catenation of all of the SCRIPTs and SCRIPT-FILEs passed
in.

   Commands within a SCRIPT or SCRIPT-FILE can be separated by
semicolons (`;') or newlines (ASCII 10).  Some commands, due to their
syntax, cannot be followed by semicolons working as command separators
and thus should be terminated with newlines or be placed at the end of
a SCRIPT or SCRIPT-FILE.  Commands can also be preceded with optional
non-significant whitespace characters.

答案 1 :(得分:1)

awk也可以有效:

s='Image.Resolution=1024x768,800x600,640x480,480x360,320x240,240x180,160x120,1280x720'
awk -F '[=,]' '{$1=""; sub(/^ */, "")} 1' <<< "$s"
1024x768 800x600 640x480 480x360 320x240 240x180 160x120 1280x720

答案 2 :(得分:1)

x="Image.Resolution=1024x768,800x600,640x480,480x360,320x240,240x180,160x120,1280x720"
x=${x#*=}             # remove left part including =
array=(${x//,/ })     # replace all `,` with whitespace and create array
echo ${array[@]}      # print array $array

输出:

1024x768 800x600 640x480 480x360 320x240 240x180 160x120 1280x720

答案 3 :(得分:1)

对于这个具体的例子,你可以用简短的方式完成:

sed 's/[^x0-9]/ /g'

x='Image.Resolution=1024x768,800x600,640x480,480x360,320x240,240x180,160x120,1280x720'
y=(${x//[^x0-9]/ })

会删除所有execpt x和数字0-9,因此输出(或数组y

1024x768 800x600 640x480 480x360 320x240 240x180 160x120 1280x720