【发布时间】:2012-03-23 23:53:24
【问题描述】:
我想在一个文本文件中搜索"\d+ [xyz]{3} \d+" 格式的三行,然后使用 sed 将这些行输出为一行。
示例输入:
...
33 xxx 7
...
33 zzz 3
...
33 yyy 5
...
输出:
33 7 3 5
【问题讨论】:
我想在一个文本文件中搜索"\d+ [xyz]{3} \d+" 格式的三行,然后使用 sed 将这些行输出为一行。
示例输入:
...
33 xxx 7
...
33 zzz 3
...
33 yyy 5
...
输出:
33 7 3 5
【问题讨论】:
使用awk:
script.awk的内容:
$1 ~ /^[[:digit:]]+$/ && $2 ~ /^[xyz]{3}$/ && $3 ~ /^[[:digit:]]+$/ {
num = $1
digits = digits " " $3
}
END {
print num digits
}
infile的内容:
text
33 xxx 7
more text
33 zzz 3
55 n
33 yyy 5
66 asf sdf
运行脚本:
awk -f script.awk infile
然后输出:
33 7 3 5
【讨论】:
sed 的一种方式:
script.sed的内容:
## Subbtitute line that matches the format with both numbers.
s/^\([0-9]\+\) [xyz]\{3\} \([0-9]\+\)$/\1 \2/
## If substitution succeed, go to label 'a'.
ta
## If substitution failed, go to label 'b'.
bb
## Save content to 'hold space'.
:a
H
## In last line, get content from 'hold space', remove numbers
## not needed in output and print.
:b
$ {
g
s/^\n//
s/\n[0-9]\+//g
p
}
infile的内容:
text
33 xxx 7
more text
33 zzz 3
55 n
33 yyy 5
66 asf sdf
运行脚本:
sed -nf script.sed infile
然后输出:
33 7 3 5
【讨论】:
这可能对你有用:
sed '/^\([0-9]\+ \)[xyz]\{3\} \([0-9]\+\)/{s//\1\2/;H};$!d;g;s/.//;s/\n[0-9]*//g' file
33 7 3 5
【讨论】: