热门标签 | HotTags
当前位置:  开发笔记 > 运维 > 正文

使用sed或awk从字符串中删除前导和尾随数字,同时保留2个数字

我有一个包含以下行的文件:353451word2423157anotherword7412yetanother13262andherese

我有一个包含以下行的文件:

353451word2423157
anotherword
7412yetanother1
3262andherese123anotherline4359013
5342512354325324523andherese123anotherline45913
532453andherese123anotherline413

我想去掉大部分前导和尾随数字(0-9),同时仍然保留 2 个前导和尾随数字,如果有的话......

澄清一下,对于上面的列表,预期的输出是:

51word24
anotherword
12yetanother1
62andherese123anotherline43
23andherese123anotherline45
53andherese123anotherline41

首选工具是 sed 或 awk,但欢迎任何其他建议...

我试过类似的东西sed 's/[0-9]+$//' | sed 's/^[0-9]+//',但显然这会去除所有前导和尾随数字......

回答

你可以试试这个sed

sed -E 's/^[0-9]+([0-9]{2})|([0-9]{2})[0-9]+$/12/g' file
51word24
anotherword
12yetanother1
62andherese123anotherline43
23andherese123anotherline45
53andherese123anotherline41

命令详情:


  • ^[0-9]+([0-9]{2}): 匹配开头的 1+ 个数字,如果后面是 2 个数字(在一个组中捕获)并替换为组 #1 中的 2 个数字。

  • ([0-9]{2})[0-9]+$: 如果前面有 2 位数字(在一组中捕获),则匹配末尾的 1+ 位数字,并替换为组 #2 中的 2 位数字。







推荐阅读
author-avatar
A梁仔乀
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有