开发者

Delete everything except all surrounded by ()

Let's say i have file like this

adsf(2)

af(3)

g5a(65)

aafg(1245)

a(3)df

How开发者_StackOverflow中文版 can i get from this only numbers between ( and ) ?

using BASH


A couple of solution comes to mind. Some of them handles the empty lines correctly, others not. Trivial to remove those though, using either grep -v '^$' or sed '/^$/d'.

sed

sed 's|.*(\([0-9]\+\).*|\1|' input

awk

awk -F'[()]' '/./{print $2}' input
2
3
65
1245
3

pure bash

#!/bin/bash

IFS="()"

while read a b; do
    if [ -z $b ]; then
        continue
    fi
    echo $b
done < input

and finally, using tr

cat input | tr -d '[a-z()]'


while read line; do
    if [ -z "$line" ]; then
        continue
    fi  
    line=${line#*(}
    line=${line%)*}
    echo $line
done < file


Positive lookaround:

$ echo $'a1b(2)c\nd3e(456)fg7' | grep -Poe '(?<=\()[0-9]*(?=\))'
2
456


Another one:

while read line ; do
  [[ $line =~ .*\(([[:digit:]]+)\).* ]] && echo "${BASH_REMATCH[1]}"
done < file
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜