shell - 使用 awk 和 gensub 删除以“字符+数字+S”结尾的字符串中的部分
问题描述
我的目标是删除结尾的“1S”以及紧接在其前面的字母,在本例中为“M”。我该如何做到这一点?我的非工作代码:
echo "14M3856N61M1S" | gawk '{gensub(/([^(1S)]*)[a-zA-Z](1S$)/, "\\1", "g") ; print $0}'
>14M3856N61M1S
期望的结果应该是
>14M3856N61
这里有一些额外的信息。1. 我认为 substr 不会在这里工作,因为我的实际目标字符串会有不同的长度。2. 我不喜欢采用定义特殊分隔符的方法,因为这将与“if”一起用作 awk 条件操作的一部分,而分隔符已经在全局范围内定义。先感谢您!
解决方案
编辑:根据 OP 的评论,我正在添加解决方案,其中 OP 也可以将结果转换为 bash 变量,如下所示。
var=$(echo "14M3856N61M1S" | awk 'match($0,/[a-zA-Z]1S$/){print substr($0,1,RSTART-1)}' )
echo "$var"
14M3856N61
您能否也尝试一下。
echo "14M3856N61M1S" | awk 'match($0,/[a-zA-Z]1S$/){$0=substr($0,1,RSTART-1)} 1'
14M3856N61
上述命令说明:
echo "14M3856N61M1S" | ##printing sample string value by echo command here and using |(pipe) for sending standard ouptut of it as standard input to awk command.
awk ' ##Starting awk command here.
match($0,/[a-zA-Z]1S$/){ ##using match keyword of awk here to match 1S at last of the line along with an alphabet(small or capital) before it too.
$0=substr($0,1,RSTART-1) ##If match found in above command then re-creating current line and keeping its value from 1 to till RSTART-1 value where RSTART and RLENGTH values are set by match out of the box variables by awk.
} ##Closing match block here.
1' ##Mentioning 1 will print the edited/non-edited values of lines here.
推荐阅读
- c# - System.InvalidOperationException: 'XML 文档 (1, 1) 中存在错误。'
- swiftui - 如何将相同的对象传递给多个子视图?
- javascript - 检测圆形和方形之间的碰撞
- excel - 匹配年份和季度的 Excel 公式然后粘贴结果
- spring - 执行 Spring Web 客户端导致 DeferringLoadBalancerExchangeFilterFunction 非限定 bean 异常
- python - 如何解决 django 中的 UnicodeDecode 错误
- c - 如何在 Tizen Native 中从手表打印心率和步数数据?
- hybris - 如何为 Hybris 2011 版本创建示例扩展
- c# - HttpServiceFactory 接口中的方法太多
- google-chrome - SameSite 无 cookie 未与跨源 IFrame 请求一起发送