开发者

Delete everything except all surrounded by ()

开发者 https://www.devze.com 2023-03-18 19:59 出处:网络
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 ) ?

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

精彩评论

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