Chinaunix首页 | 论坛 | 博客
  • 博客访问: 595094
  • 博文数量: 248
  • 博客积分: 52
  • 博客等级: 民兵
  • 技术积分: 1028
  • 用 户 组: 普通用户
  • 注册时间: 2012-12-23 12:05
文章分类

全部博文(248)

文章存档

2016年(7)

2013年(241)

分类: LINUX

2013-04-07 22:27:24

 假设有"123abc456def789ghi"这么一个字符串
题中的字符串,要截取长度5,则返回的字符串应该为:123ab,要截取长度8,应返回123abc45。
附:
标记不得计算在长度之内。
2 截取后的字符串,要保留原有标签,不过如果最后有一个标签没有闭合,则去掉其开始标签。

代码:如下
  1. #!/bin/bash
  2. a='123abc456def789ghi'
  3. echo "test text is '$a'"
  4. read -p "please input a number little than `echo $a|awk '{gsub("<em>|</em>","",$0);printf length($0)}'`: " num

  5. echo $a | awk -vnum="$num" -vFS='' '{for(i=1;i<=NF;i++){orisum=sum;sum+=length($i)-4;if(sum<=num){strlist=strlist ~ /./ ? strlist""FS""$i : $i}else{sub("","",$i);strlist=strlist ~ /./ ? strlist""FS""substr($i,1,num-orisum) : substr($i,1,num-orisum);break}}print strlist}'

测试结果:

  1. [root@localhost ~]# bash 1.sh
  2. test text is '123abc456def789ghi'
  3. please input a number little than 18: 2
  4. 12
  5. [root@localhost ~]# bash 1.sh
  6. test text is '123abc456def789ghi'
  7. please input a number little than 18: 5
  8. 123ab
  9. [root@localhost ~]# bash 1.sh
  10. test text is '123abc456def789ghi'
  11. please input a number little than 18: 7
  12. 123<em>abc</em>4
  13. [root@localhost ~]# bash 1.sh
  14. test text is '123abc456def789ghi'
  15. please input a number little than 18: 10
  16. 123<em>abc</em>456d
  17. [root@localhost ~]# bash 1.sh
  18. test text is '123abc456def789ghi'
  19. please input a number little than 18: 9
  20. 123<em>abc</em>456
  21. [root@localhost ~]# bash 1.sh
  22. test text is '123abc456def789ghi'
  23. please input a number little than 18: 14
  24. 123<em>abc</em>456<em>def</em>78
  25. [root@localhost ~]# bash 1.sh
  26. test text is '123abc456def789ghi'
  27. please input a number little than 18: 17
  28. 123<em>abc</em>456<em>def</em>789gh
  29. [root@localhost ~]# bash 1.sh
  30. test text is '123abc456def789ghi'
  31. please input a number little than 18: 18
  32. 123<em>abc</em>456<em>def</em>789<em>ghi</em>
  33. [root@localhost ~]#




阅读(651) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~