首页 > 解决方案 > How to cut string="Domain_12345_20180821230101.dat" into 12345_20180821 in Bash

问题描述

Provided that this sting is dynamic. If it is as Domain_1234_20180821230101.dat then I want 1234_20180821. How can I do that?

I.e., when Domain_12_20180821230101.dat then I want output as 12_20180821

标签: linuxbash

解决方案


适用于您提供的示例的原始解决方案是:

grep -oP '[0-9]+_[0-9]{8}' <<< "$string"

这将提取由可变长度数字组成的任何子字符串,后跟一个下划线,后跟一个 8 位数字(如果存在),否则不返回任何内容。

您可以在https://www.regular-expressions.info/tutorial.htmlgrep --help下找到更多信息来帮助您理解此命令并根据需要进行调整以适应您的要求。


推荐阅读