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

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

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 位数字。

以上是使用sed或awk从字符串中删除前导和尾随数字,同时保留2个数字的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>