格式化文件中特定行号后的格式

时间:2022-11-27 13:56:28

I am running a while loop in a script ro read a file line by line.

我在脚本中运行while循环ro逐行读取文件。

Now I want to run a grep only on the lines below the line I am that is being read by the while loop.

现在我想只在我正在被while循环读取的行下面的行上运行grep。

Eg:

If my while loop is on line 4 of the file, the grep only runs below line 4 and does not include line 1,2 and 3.

如果我的while循环位于文件的第4行,则grep仅在第4行下运行,不包括第1,2和3行。

How is that achievable ?

这怎么可以实现?

Regards.

2 个解决方案

#1


You can't do it with grep alone, but you can if you use its friends:

你不能单独使用grep来做,但如果你使用它的朋友你就可以:

tail +100 file_im_searching | grep pattern_i_want

Using the + option you can tell tail how far into the file to start. If you kept track of your line number in the while loop, you could do something like this:

使用+选项可以告诉tail要启动文件的距离。如果你在while循环中跟踪你的行号,你可以这样做:

tail +$LINENUMBER file | grep pattern

Looking at the details of your question, however, I wonder if you'd be better off passing the line that you have through grep or sed or something..

然而,看看你的问题的细节,我想知道你是否会更好地通过grep或sed等传递你的线路。

For example, supposing that you have read your line into variable LINE, perhaps:

例如,假设您已将行读入变量LINE,可能:

set RESULT = $(echo $LINE | grep stuff_to_search_for)

#2


This sounds like what you are asking for:

这听起来像你要求的:

awk 'NR>3 && /regexp/' file

but every time you write a loop in shell just to manipulate text you have the wrong approach so if that's what you are doing then post sample input/output if you'd like to see the right way to do it.

但是每次你在shell中编写一个循环只是为了操作文本你都有错误的方法,所以如果这就是你正在做的事情,那么如果你想看到正确的方法,那就发布样本输入/输出。

#1


You can't do it with grep alone, but you can if you use its friends:

你不能单独使用grep来做,但如果你使用它的朋友你就可以:

tail +100 file_im_searching | grep pattern_i_want

Using the + option you can tell tail how far into the file to start. If you kept track of your line number in the while loop, you could do something like this:

使用+选项可以告诉tail要启动文件的距离。如果你在while循环中跟踪你的行号,你可以这样做:

tail +$LINENUMBER file | grep pattern

Looking at the details of your question, however, I wonder if you'd be better off passing the line that you have through grep or sed or something..

然而,看看你的问题的细节,我想知道你是否会更好地通过grep或sed等传递你的线路。

For example, supposing that you have read your line into variable LINE, perhaps:

例如,假设您已将行读入变量LINE,可能:

set RESULT = $(echo $LINE | grep stuff_to_search_for)

#2


This sounds like what you are asking for:

这听起来像你要求的:

awk 'NR>3 && /regexp/' file

but every time you write a loop in shell just to manipulate text you have the wrong approach so if that's what you are doing then post sample input/output if you'd like to see the right way to do it.

但是每次你在shell中编写一个循环只是为了操作文本你都有错误的方法,所以如果这就是你正在做的事情,那么如果你想看到正确的方法,那就发布样本输入/输出。