[英]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
但是它不会捕获以非#
开头的非字母数字字符的文本行,例如提交消息以表情符号、破折号、括号等开头。
To catch all edge cases you can loop through the file and check each $line
with a negated !
要捕获所有边缘情况,您可以遍历文件并使用否定检查每个
$line
!
regexp operator =~
for:正则表达式运算符
=~
用于:
! $line =~ (^[^\n ]*$)
! $line =~ (^[^\n ]*$)
! $line =~ (^[^\n ]*$)
! $line =~ ^#
! $line =~ ^#
! $line =~ ^#
! $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.