gpt4 book ai didi

bash - 如何获取匹配的行号?

转载 作者:行者123 更新时间:2023-11-29 09:13:57 25 4
gpt4 key购买 nike

我的目标是获取与 /etc/crontab 中的一行匹配的字符串的行号($lineof)。

0 8 * * * Me echo "start working please" 并得到 这是来自/etc/crontab 的第 13 行

给定这个文件 /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

目前我正在做类似的事情:

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

$nbline give me the line of the content in /tmp/task.cron

$LINENO give me the line of the current script (which execute the program)

I want $lineof give me the number of the line in /etc/crontab

最佳答案

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

grep -Fn 'your_line' /etc/crontab

但是,由于您想打印一些消息和行号,您可能想改用 awk:

awk -v line='your_line' '$0 == line {print "this is the line number", NR, "from", FILENAME}' /etc/crontab

测试

$ 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

使用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

使用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"

关于bash - 如何获取匹配的行号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31431991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com