在 bash 脚本中获取第一行未注释的行(即不以 # 开头)

Get first uncommented line (i.e not staring with #) in bash script

我正在 git 挂钩中处理开发人员提交消息。

假设文件有以下内容


\n new lines here
# this is a sample commit
# only for the developers
Ticket-ID: we fix old bugs and introduces new ones
we always do this stuff

so cool, not really :P
# company name

我的意图是只得到这一行Ticket-ID : we fix old bugs and introduces new ones

User123 的评论简洁明了:grep -E "^[[:alnum:]]" file |head -n 1 然而 not 捕获以非字母数字字符开头的文本行,这些字符不是 # 例如以表情符号、破折号、括号等开头的提交消息。

  • 是的,这一行是个例外
  • --> 这也是一个边缘案例
  • (这个也是)

要捕获所有边缘情况,您可以遍历文件并使用取反的 ! 正则表达式运算符 =~ 检查每个 $line for:

  1. 不是换行符! $line =~ (^[^\n ]*$)
  2. 不是以井号开头! $line =~ ^#
  3. 不是由所有空格组成的行! $line =~ (^[ ]*$)

然后 echo $linebreak 如果满足这些条件:

# file parse.sh
#!/bin/bash
if [[ -f  ]]; then
  while IFS= read -r line
  do
    [[ ! $line =~ (^[^\n ]*$) && ! $line =~ ^# && ! $line =~ (^[ ]*$) ]] && echo "$line" && break
  done < ""
fi
# file commit .txt


# this is a sample commit
# only for the developers
Ticket-ID: we fix old bugs and introduces new ones
we always do this stuff

so cool, not really :P
# company name

现在您可以像这样调用 parse.sh

bash parse.sh commit.txt

或者使用子 shell 将结果保存到变量

result=$(bash parse.sh commit.txt); echo "$result"

下面的单行 grep 应该可以满足您的要求:

grep -E "^[[:alnum:]]" file |head -n 1

解释:

^[[:alnum:]] :: to capture only the line starting with any alphanumeric character[0-9A-Za-z]

head -n 1 ::  to capture the first occurrence