Sed正则表达式和后向引用

时间:2013-09-20 14:40:03

标签: regex bash sed

我想从格式的网络组(hostname ,,)中提取主机名。我使用了以下sed命令。似乎它们都不起作用。谁能指出我正确的正则表达式构造?感谢。

bash-3.2# ypcat -k netgroup|grep '^gridprod2 '|sed 's/(\([a-zA-Z0-9]*\),,)/\1\n/g'
gridprod2 (sbpsvrso766,,) (sbpsvrso767,,) (sbpsvrso768,,) (sbpsvrso769,,) (sbpsvrso461,,) (sbpsvrso462,,) (sbpsvrso463,,) (sbpsvrso464,,) (sbpsvrso465,,) (sbpsvrso466,,) (sbpsvrso467,,)  (sbpsvrso468,,) (sbtorsvr569,,) (sbpsvrwm841,,) (sbpsvrwm842,,) (sbpsvrwm843,,) (sbpsvrwm844,,) (sbpsvrwm845,,) (sdpsvrso804,,)

bash-3.2# ypcat -k netgroup|grep '^gridprod2 '|sed 's/(\([:alnum:]*\),,)/\1\n/g'
gridprod2 (sbpsvrso766,,) (sbpsvrso767,,) (sbpsvrso768,,) (sbpsvrso769,,) (sbpsvrso461,,) (sbpsvrso462,,) (sbpsvrso463,,) (sbpsvrso464,,) (sbpsvrso465,,) (sbpsvrso466,,) (sbpsvrso467,,)  (sbpsvrso468,,) (sbtorsvr569,,) (sbpsvrwm841,,) (sbpsvrwm842,,) (sbpsvrwm843,,) (sbpsvrwm844,,) (sbpsvrwm845,,) (sdpsvrso804,,)

2 个答案:

答案 0 :(得分:0)

使用grep -oP代替lookbehind

echo "gridprod2 (sbpsvrso766,,) (sbpsvrso767,,) (sbpsvrso768,,) (sbpsvrso769,,) (sbpsvrso461,,) (sbpsvrso462,,) (sbpsvrso463,,) (sbpsvrso464,,) (sbpsvrso465,,) (sbpsvrso466,,) (sbpsvrso467,,)  (sbpsvrso468,,) (sbtorsvr569,,) (sbpsvrwm841,,) (sbpsvrwm842,,) (sbpsvrwm843,,) (sbpsvrwm844,,) (sbpsvrwm845,,) (sdpsvrso804,,)" \
| grep ^gridprod2 | grep -oP '(?<=\()[^,\)]*'

输出:

sbpsvrso766
sbpsvrso767
sbpsvrso768
sbpsvrso769
...

可能更精确的是

grep -oP '(?<=\().*?(?=,,\))'

答案 1 :(得分:0)

awk版本:

awk -F, 'NR>1 {print $1}' RS="(" file
sbpsvrso766
sbpsvrso767
sbpsvrso768
sbpsvrso769
.....