首页 > 解决方案 > 使用 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 条件操作的一部分,而分隔符已经在全局范围内定义。先感谢您!

标签: shelldesign-patternsawksubstitution

解决方案


编辑:根据 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.

推荐阅读