在两个括号之间打印字符串


14

我有这些行的文件

G8 = P(G1,G3)
G9 = P(G3,G4)
G12 = P(G2,G9)
G15 = P(G9,G5)
G16 = P(G8,G12)
G17 = P(G12,G15)

我需要输出为

G1,G3
G3,G4
.....

我该如何使用sed / grep命令或使用perl?

Answers:


18

其他几种方式:

  • sed

    sed 's/.*(\(.*\))/\1/' file 
  • 佩尔

    perl -pe 's/.*\((.*)\)/$1/' file 

    要么

    perl -lanF"[()]" -e 'print $F[1]' file 

    要么

    perl -pe 's/.*\((.+?)\).*/$1/;' file 
  • awk

    awk -F"[()]" '{print $2}' file 
  • 贝壳

    while IFS="()" read a b; do echo "$b"; done < file 

您能进一步了解awk方法的工作原理吗,它也很容易记住
satch_boogie

1
@satch_boogie -F允许您选择awk将用于将行拆分为字段的字符。在这里,我给它一个字符类([]),其中包含左括号和右括号。因此,将分为上线(和上)。结果,第二字段将成为括号的内容。例如,用字符串G8 = P(G1,G3)foo$1G8 = P$2G1,G3$3foo
terdon

7

有多种方法可以做到这一点:

perl -nle 'print $1 if /\((.*)\)/' file

要么:

awk 'NR > 1 {print $1}' RS='(' FS=')' file

5
grep -oP '\(\K[^)]+' file

查找开头括号,将其忽略,然后打印其后的所有非闭合括号字符。

需要GNU grep


5

sed 's/^.*(//;s/)$//' /path/to/file

要对此进行分解:

seds筹款人ed's/^.*(//;s/)$//'是要发送到的脚本sed,其分解如下:

s/^.*(//    substitute nothing for the beginning of any line (`^`) followed by anything up until an open-paren (`(`)
s/)$//      substitute nothing for a close-paren (`)`) followed immediately by the end of a line

1

一个简单的解决方案:

$ cat test01 | cut -d“(” -f2 | cut -d“)” -f1


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.