[英]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 can i get from this only numbers between ( and )?我怎样才能从(和)之间的唯一数字中得到?
using BASH使用 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'
.不过,使用grep -v '^$'
或sed '/^$/d'
删除这些内容很简单。
sed sed
sed 's|.*(\([0-9]\+\).*|\1|' input
awk awk
awk -F'[()]' '/./{print $2}' input
2
3
65
1245
3
pure bash纯bash
#!/bin/bash
IFS="()"
while read a b; do
if [ -z $b ]; then
continue
fi
echo $b
done < input
and finally, using tr
最后,使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.