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



我正在githook中处理一条开发人员提交消息。

假设该文件具有以下内容


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并没有捕获以非#的非字母字符开头的文本行,例如以表情符号、破折号、括号等开头的提交消息。

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

要捕获所有边缘情况,您可以在文件中循环,并使用否定的!正则表达式运算符=~检查每个$line

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

如果满足这些条件,则仅为echo$linebreak

# file parse.sh
#!/bin/bash
if [[ -f $1 ]]; then
while IFS= read -r line
do
[[ ! $line =~ (^[^n ]*$) && ! $line =~ ^# && ! $line =~ (^[ ]*$) ]] && echo "$line" && break
done < "$1"
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

相关内容

最新更新