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