删除()之前和之后的文本

时间:2011-04-18 10:04:27

标签: sed awk grep

如何删除文本直到第一个(及之后)?

INSERT INTO `todel` VALUES (1,'akbar\'s','Mumbai, Delhi road, India');
INSERT INTO `todel` VALUES (2,'amar\"s','South Africa, ghana');

预期的输出是这样的......

1,'akbar\'s','Mumbai, Delhi road, India'
2,'amar\"s','South Africa, ghana'

3 个答案:

答案 0 :(得分:2)

红宝石(1.9 +)

$> ruby -ne 'print $_.sub(/.*\(|\).*$/,"")' file
1,'akbar\'s','Mumbai, Delhi road, India'
2,'amar\"s','South Africa, ghana'

或shell(bash)

$> while read -r line; do line=${line#*(}; echo ${line%)*}; done <file
1,'akbar\'s','Mumbai, Delhi road, India'
2,'amar\"s','South Africa, ghana'

或awk

$> awk '{sub(/.*\(/,"");sub(/\).*/,"")}1' file
1,'akbar\'s','Mumbai, Delhi road, India'
2,'amar\"s','South Africa, ghana'

或sed

$> sed -rn 's/.*\(//;s/\).*//p' file
1,'akbar\'s','Mumbai, Delhi road, India'
2,'amar\"s','South Africa, ghana'

答案 1 :(得分:1)

awk可以将正则表达式作为字段分隔符,因此使用括号作为字段分隔符,只发出第二个字段:

awk -F'[()]' '{print $2}' filename

答案 2 :(得分:0)

您可以删除从行首到第一个(以及从(包括)最后)sed行结尾的所有内容:

sed -r 's/^[^(]*\(.*)\)[^)]*$/\1/'