0

I have a file like this

x   +   chrX    15362   15364   +   100(3)  *(0)    *(0)    *(0)    100(5)  *(0)    100(1)
y   +   chrX    153626  153626  +   100(80) 98.56(79)   100(40) 100(47) 100(88) 4(23)

I want to capture the values within parenthesis and just print them so that the output looks like this

x   +   chrX    15362   15364   +   3   0   0   0   5   0   1
y   +   chrX    153626  153626  +   80  79  40  47  88  23

I want to do this in sed.

I tried something like this but it is not working

sed -r 's/^.*\((\d+)\)/\1/g'

Also how can I get rid of everything within the parenthesis including the parenthesis so that I get the following output also

x   +   chrX    15362   15364   +   100 *   *   *   100 *   100
y   +   chrX    153626  153626  +   100 98.56   100 100 100 4
1
$ sed 's/([^)]*)//g' file
x   +   chrX    15362   15364   +   100  *    *    *    100  *    100
y   +   chrX    153626  153626  +   100 98.56   100 100 100 4

Here, we use sed to remove any parenthesis in the input. The expression ([^)]*) matches a left parenthesis followed by any number of non-right parenthesis characters (i.e. the number), followed by a right parenthesis. You could also use ([0-9]*) here.

$ sed 's/[^[:blank:]]*(\([^)]*\))/\1/g' file
x   +   chrX    15362   15364   +   3  0    0    0    5  0    1
y   +   chrX    153626  153626  +   80 79   40 47 88 23

Here, we delete the bit before the parenthesis, and the parentheses themselves, and replace all of that with the thing that was inside the parenthesis. The stuff before the ( is matched by [^[:blank:]]*, i.e. any number of non-blank characters, followed by the same expression as in the first sed command, but capturing the contents between ( and ). The captured string is referenced in the replacement part of the command by \1.


Your command,

sed -r 's/^.*\((\d+)\)/\1/g'

does not work properly because \d is a PCRE (a Perl-like regular expression). Replacing \d with [0-9] or [[:digit:]] would not make it work better as it would replace the whole line with the number inside the last parenthesis.

  • For the first part of your answer what is [^ doing? – user3138373 Sep 6 '18 at 16:57
  • @user3138373 [^)] matches one character that is not ). – Kusalananda Sep 6 '18 at 16:59
1

Try this: sed -r 's/[^[:blank:]]*\(([[:digit:]]+)\)/\1/g'

  • finds zero or more non-whitespace chars followed by open paren followed by digits (capture) followed by close paren
  • replace with just the captured digits
  • do that globally in the line
  • \d is a PCRE construct, not from extended regex

Pipe the output into | column -t for prettiness.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.