简体   繁体   English

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

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

I am processing a developer commit message in git hook.我正在 git 挂钩中处理开发人员提交消息。

let's say the file has the following content假设该文件具有以下内容


\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

My intention is to get only this line Ticket-ID: we fix old bugs and introduces new ones我的意图是只获得这一行Ticket-ID: we fix old bugs and introduces new ones

User123's comment is nice and terse: grep -E "^[[:alnum:]]" file |head -n 1 however is does not catch lines of text that start with non-alphanumeric characters that are not a # such as commit messages that start with an emoji, dashes, parenthesis, etc.. User123 的评论简洁明了: grep -E "^[[:alnum:]]" file |head -n 1但是它不会捕获以非#开头的非字母数字字符的文本行,例如提交消息以表情符号、破折号、括号等开头。

  • yeah this line is an exception是的,这条线是个例外
  • --> This is also an edge case --> 这也是一个边缘情况
  • (so is this) (这个也是)

To catch all edge cases you can loop through the file and check each $line with a negated !要捕获所有边缘情况,您可以遍历文件并使用否定检查每个$line ! regexp operator =~ for:正则表达式运算符=~用于:

  1. Not being a newline ! $line =~ (^[^\n ]*$)不是换行符! $line =~ (^[^\n ]*$) ! $line =~ (^[^\n ]*$)
  2. Not starting with a pound sign ! $line =~ ^#不是以英镑符号开头! $line =~ ^# ! $line =~ ^#
  3. Not being a line consisting of all spaces ! $line =~ (^[ ]*$)不是由所有空格组成的行! $line =~ (^[ ]*$) ! $line =~ (^[ ]*$)

Then just echo the $line and break if those conditions are met:然后只需echo$line并在满足这些条件时break

# 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

Now you can invoke the parse.sh like this现在您可以像这样调用parse.sh

bash parse.sh commit.txt

Or save the results to a variable using a subshell或者使用子shell将结果保存到变量中

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

Below single line grep should work as per your requirement:下面的单行grep应该按照您的要求工作:

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

Explanation:解释:

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

head -n 1 ::  to capture the first occurrence

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM