本文主要讲如下四种正则表达式:
- Basic regular expressions (BRE)
- Extended regular expressions (ERE)
- Perl-compatible regular expressions (PCRE)
- Vim pattern
正当我准备手打一个上述四种正则表达式的参考手册时,我不小心发现了这个: Regex cheatsheet
天啦噜,这个也太棒了吧
遇到过的问题
- shell - grep with line breaks - Unix & Linux Stack Exchange
- Use script to get C language function declaration - Programmer Sought:
1
grep -hzoP '\s*[a-zA-Z_][a-zA-Z_0-9]*(\s*\*+\s*|\s+)[a-zA-Z_][a-zA-Z_0-9]*\s*\([a-zA-Z_0-9*(),\s]+\)\s*[;{]' a.c a.h
例子
提取--help
中的必要信息
我想知道rsync
命令中的-a
参数有什么用,于是:
1
2
# rsync --help |grep -E '^[ ]+-a'
-a, --archive archive mode; equals -rlptgoD (no -H,-A,-X)
因此,我想得到-rlptgoD
这几个参数的作用,像这样:
1
2
3
4
5
6
7
8
9
-r, --recursive recurse into directories
-l, --links copy symlinks as symlinks
-p, --perms preserve permissions
-o, --owner preserve owner (super-user only)
-g, --group preserve group
--devices preserve device files (super-user only)
--specials preserve special files
-D same as --devices --specials
-t, --times preserve modification times
使用grep
命令很容易达到这个目的:
- BRE:
rsync --help |grep '^[ ]\+\(-[rlptgoD]\|--devices\|--specials\)'
- ERE:
rsync --help |grep -E '^[ ]+(-[rlptgoD]|--devices|--specials)'
- PCRE:
rsync --help |grep -P '^[ ]+(-[rlptgoD]|--devices|--specials)'
将其封装为一个 bash 函数是个不错的想法:
1
2
3
4
5
6
7
8
hg ()
{
local command="$1";
shift;
"$command" --help 2>&1 | grep --color=auto -- "$@"
}
hg rsync -a
hg rsync '^[ ]\+\(-[rlptgoD]\|--devices\|--specials\)'