最后出现尴尬模式的行数

发布于 2025-02-07 11:05:24 字数 228 浏览 4 评论 0原文

我是Awk命令的新手。我正在尝试一种方法来打印我的模式匹配的最后一行号码。 我需要将该尴尬命令集成到TCL脚本中。 如果有人回答,请告诉我。

exec awk -v search=$var {$0~search{print NR; exit}} file_name

我正在使用它打印第一次出现的行号。

I am new to awk commands. I am trying a way to print the last line number for my pattern match.
I need to integrate that awk command in tcl script..
If someone has answer to it, please let me know.

exec awk -v search=$var {$0~search{print NR; exit}} file_name

I am using this to print the line number of first occurrence.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

甩你一脸翔 2025-02-14 11:05:24

我会在此任务上使用awk awk 以下,令file.txt

12
15
120
150
1200
1500

输出

awk '$0~"12"{n=NR}END{print n}' file.txt

说明

5

:我正在寻找包含12的最后一行。 ,当遇到此类行时,我将变量的n的值设置为行数(nr),当处理所有行线时,i print> print所说的价值。

(在GAWK 4.2.1中测试)

I would harness GNU AWK for this task following, let file.txt content be

12
15
120
150
1200
1500

then

awk '$0~"12"{n=NR}END{print n}' file.txt

output

5

Explanation: I am looking for last line containing 12 somewhere, when such line is encountered I set value of variable n to number of row (NR), when all lines of lines are processed I print said value.

(tested in gawk 4.2.1)

半山落雨半山空 2025-02-14 11:05:24

或者,没有awk

set fh [open file_name]
set lines [split [read $fh] \n]
close $fh
set line_nums [lmap idx [lsearch -all -regexp $lines with] {expr {$idx + 1}}]
set last_line_num [lindex $line_nums end]

Or, without awk:

set fh [open file_name]
set lines [split [read $fh] \n]
close $fh
set line_nums [lmap idx [lsearch -all -regexp $lines with] {expr {$idx + 1}}]
set last_line_num [lindex $line_nums end]
能怎样 2025-02-14 11:05:24

在您显示的样本和努力下,请尝试以下TAC + awk代码。

tac Input_file | 
awk -v lines=$(wc -l < Input_file) '/12/{print lines-FNR+1;exit}'

说明:

  • 使用tac命令以从底部到顶部以相反的顺序打印input_file的输出从awk程序中,稍后解释)。
  • 发送TAC INPUT_FILE输出到awk程序作为输入。
  • 中awk程序创建变量命名lines具有Input_file行的总数,在主程序中检查行是否包含12然后打印 lines-fnr+1 值,并使用退出从程序中退出,我们不需要读取整个input_file。

With your shown samples and efforts please try following tac + awk code.

tac Input_file | 
awk -v lines=$(wc -l < Input_file) '/12/{print lines-FNR+1;exit}'

Explanation:

  • Using tac command to print Input_file's output in reverse order from bottom to top(basically to get very last match very quickly at first and exit from awk program, explained later on).
  • Sending tac Input_file output to awk program as an input.
  • In awk program creating variable named lines which has total number of lines of Input_file and in main program checking if line contains 12 then printing lines-FNR+1 value and using exit exiting from program then, by which we need NOT to read whole Input_file.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文