如何获取匹配的行号?

Jér*_*émy 5 bash grep pattern-matching string-split

我的目标是获取与/etc/crontab.

给予0 8 * * * Me echo "start working please"和得到this is the line number 13 from /etc/crontab

鉴于此文件/tmp/crontab

# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user  command
#
0 17 * * * Me echo "end of work"
0 8 * * * Me echo "start working please"
1 3 2 4 2 Me ls -la
Run Code Online (Sandbox Code Playgroud)

我暂时做这样的事情:

cat /etc/crontab | grep -v "#" | grep "Me" > /tmp/task.cron
i=1
while read -r content
do
        line=$content
        # lineof=$LINENO
        nbline=${i}
        minute=$(echo "$line" | awk '{print $1}')  #0-59
        hour=$(echo "$line" | awk '{print $2}')    #0-23
        dom=$(echo "$line" | awk '{print $3}')     #1-31
        month=$(echo "$line" | awk '{print $4}')   #1-12
        dow=$(echo "$line" | awk '{print $5}')     #0-6 (0=Sunday)
        cmd=$(echo "$line" | awk '{$1=$2=$3=$4=$5=$6=""; print $0}')    #command
        cmd=$(echo "$cmd" | tr ' ' _)
        str=$str' '$nbline' "'$minute'" "'$hour'" "'$dom'" "'$month'" "'$dow'" "'$user'" "'$cmd'" '
        i=$(($i+1))
done < /tmp/task.cron
Run Code Online (Sandbox Code Playgroud)

$nbline给我/tmp/task.cron中的内容

$LINENO 给我当前脚本的行(执行程序)

我想$lineof给我/etc/crontab中的行号

Alb*_*lla 6

grep --fixed-strings --line-number "${match}" | grep --fixed-strings --line-number "${match}" | 剪切--delimiter=":" --fields=1


fed*_*qui 5

要打印匹配的行号,请使用-n选项grep。由于模式包含一些特殊字符,使用-F使它们被解释为固定字符串而不是正则表达式:

grep -Fn 'your_line' /etc/crontab
Run Code Online (Sandbox Code Playgroud)

但是,由于您想与行号一起打印一些消息,您可能需要使用awk

awk -v line='your_line' '$0 == line {print "this is the line number", NR, "from", FILENAME}' /etc/crontab
Run Code Online (Sandbox Code Playgroud)

测试

$ cat a
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user  command
#
0 17 * * * Me echo "end of work"
0 8 * * * Me echo "start working please"
1 3 2 4 2 Me ls -la
Run Code Online (Sandbox Code Playgroud)

awk

$ awk -v line='0 8 * * * Me echo "start working please"' '$0 == line {print "this is the line number", NR, "from", FILENAME}' a
this is the line number 13 from a
Run Code Online (Sandbox Code Playgroud)

grep

$ grep -Fn '0 8 * * * Me echo "start working please"' a13:0 8 * * * Me echo "start working please"
13:0 8 * * * Me echo "start working please"
Run Code Online (Sandbox Code Playgroud)