首页 > 解决方案 > 在 shell 脚本上选择一个模式之前和之后的一个单词(连字符是模式)

问题描述

使用 shell 脚本在模式(连字符是模式)之前和之后选择一个单词。

Out 是一个包含数百行的文本文件,我选择了具有必需 ID 的文本文件,但是我需要选择 ALPHABETS-NUMBERS。字母和数字的计数各不相同。

我尝试了各种实用程序,包括 cut、sed、awk,但它会修剪所需的字段。

输入

cat out | grep "[A-Z][-][0-9]"
BUG-KEYWORD-BUG-101
ABC-10
DEF-10327
Output is referred in ABC-1043
Please refer DEF-11234

输出应该是

BUG-101
ABC-10
DEF-10327
ABC-1043
DEF-11234

标签: shellawksed

解决方案


请您尝试以下操作。用 GNU 中的示例编写和测试awk

awk 'match($0,/[a-zA-Z]+-[0-9]+$/){print substr($0,RSTART,RLENGTH)}' Input_file

说明:为上述添加详细说明。

awk '                               ##Starting awk program from here.
match($0,/[a-zA-Z]+-[0-9]+$/){      ##using match function to match alphabets dash and digits till last of line.
  print substr($0,RSTART,RLENGTH)   ##Printing matches sub string of matched regex.
}
' Input_file                        ##Mentioning Input_file name here.

推荐阅读