如何在 shell 脚本中匹配变量中的字符后提取字符串

How to extract a string after matching characters from a variable in shell script

我有一个包含以下文本的文件

classA = Something
classB = AB1234567
classC = Something more
classD = Something Else

Objective:
使用 shell 脚本,我想从上面的完整文本中读取 AB1234567 的文本。

因此,首先,我可以在我的 shell 脚本中使用以下逻辑阅读上述文本的第二行:

secondLine=`sed -n '2p' my_file`;
echo $secondLine;

secondLine 输出 classB = AB1234567。如何在我的 shell 脚本中从 classB = AB1234567 中提取 AB1234567

问题:
考虑到 AB 在我处理的所有文件的文本的特定部分很常见,我怎样才能让 sed 读取 AB 之后的所有数字?

请注意 classB = AB1234567 可以以 space 或换行符结尾。 我需要把它变成一个变量

你可以试试这个awk:

awk -F ' *= *' ' ~ /B$/ { print  }' file
AB1234567

尝试:

sed '2{ s/^classB = \(AB[^ ]*\) *$//;q } ;d' your_fileName
  • 2是行号。
    • { 打开一个 sed 组命令。
      • s/ 在比赛下方替换
        • ^ 是行首的锚点
        • \(...\) 是已知的捕获组,其 </code> 作为其 back-reference<br></li> <li><code>[^ ]* 表示任何字符,但不包括 space
        • \(AB[^ ]*\) 捕获 AB,然后是任何东西,直到第一个 space 看到但没有 spaces(back-reference 是 </code>)<br></li> <li><code> *表示zero-or-morespaces
        • $ 是行尾的锚点
      • / 与下面
        • </code> back-reference 以上捕获组</li> </ul> </li> <li><code>/替换结束
        • q 退出以避免不必要地读取文件的其余部分
      • }关闭组命令。
    • d 删除第 2 行之前的任何其他行。

    进入变量:

    your_variableName=$(sed '2{ s/^classB = \(AB[^ ]*\) *$//;q } ;d' your_fileName)
    

能否请您尝试以下,在awk中看起来应该很容易。考虑到您要打印第二行并仅打印最后一个字段中的数字。

secondLine=$(awk 'FNR==2{sub(/[^0-9]*/,"",$NF);print $NF}' Input_file)

我不是 100% 确定这就是您要查找的内容,但如果您知道文件中只有一个以 AB 开头的元素,这会将其放入一个变量中:

$ cat sample.txt 
classA = Something
classB = AB1234567
classC = Something more
classD = Something Else
  
$ x=$(perl -ne 'print if s/^.*\s+(AB\S+)\s*$//' sample.txt)
 
$ echo "the variable is: $x"
the variable is: AB1234567

正则表达式的解释:

  • ^行首
  • .*任何东西
  • \s+任意个空格
  • (AB\S+) 任何以 AB 开头后跟 non-spaces
  • 的内容
  • \s*$ 零个或多个空格后跟行尾。