闲来练习一下正则表达式,提取一下×××号中的出生年月日,大家能给出些其他更高效的方法吗?
- #!/bin/bash
- #get the birthday from the id number
- echo 423256198310310048 > idnum.txt
- #get the string of year from id number txt
- cat idnum.txt | sed -e 's/^[[:alnum:]]\{6\}//'|sed -e 's/[[:alnum:]]\{8\}$//'|tr -d '\n'
- printf "-"
- #get the string of month from id number txt
- cat idnum.txt | sed -e 's/^[[:alnum:]]\{10\}//'|sed -e 's/[[:alnum:]]\{6\}$//'|tr -d '\n'
- printf "-"
- #get the string of day from id number txt
- cat idnum.txt | sed -e 's/^[[:alnum:]]\{12\}//'|sed -e 's/[[:alnum:]]\{4\}$//'|tr -d '\n'
- printf "\n"
- rm -f idnum.txt
改进了一下shell,不用写入到text文本里,
- echo 510105198310310048 | sed -e 's/^[[:alnum:]]\{6\}//' -e 's/[[:alnum:]]\{4\}$//' -e 's/^[[:alnum:]]\{6\}/&-/' -e 's/^[[:alnum:]]\{4\}/&-/'
#-------------------尝试用Perl的正则表达式来匹配替换--------------------
- #! /usr/bin/perl
- $str = " 423256198310310048 ";
- $str =~ s/^\d{6}//;
- $str =~ s/\d{4}$//;
- $str =~ s/^\d{4}/$&-/;
- $str =~ s/\d{2}$/-$&/;
- print $str;
感觉Perl非常的简洁清晰、方便。
转载于:https://blog.51cto.com/carllai/945159