How to get the part of file after the line that ma

2019-01-05 07:10发布

I have a file with about 1000 lines. I want the part of my file after the line which matches my grep statement.

i.e.

$ cat file | grep 'TERMINATE'     // Its found on line 534

So, I want the file from line 535 to line 1000 for further processing.

How do I do it ?

12条回答
聊天终结者
2楼-- · 2019-01-05 07:42

If for any reason, you want to avoid using sed, the following will print the line matching TERMINATE till the end of the file:

tail -n "+$(grep -n 'TERMINATE' file | head -n 1 | cut -d ":" -f 1)" file

and the following will print from the following line matching TERMINATE till the end of the file:

tail -n "+$(($(grep -n 'TERMINATE' file | head -n 1 | cut -d ":" -f 1)+1))" file

It takes 2 processes to do what sed can do in one process, and if the file changes between the execution of grep and tail, the result can be incoherent, so I recommend using sed. Moreover, if the file dones not contain TERMINATE, the 1st command fails.

查看更多
我只想做你的唯一
3楼-- · 2019-01-05 07:44

Alternatives to the excellent sed answer by jfgagne, and which don't include the matching line :

查看更多
一纸荒年 Trace。
4楼-- · 2019-01-05 07:46

Use bash parameter expansion like the following:

content=$(cat file)
echo "${content#*TERMINATE}"
查看更多
在下西门庆
5楼-- · 2019-01-05 07:46

grep -A 10000000 'TERMINATE' file

  • is much, much faster than sed especially working on really big file. It works up to 10M lines (or whatever you put in) so no harm in making this big enough to handle about anything you hit.
查看更多
三岁会撩人
6楼-- · 2019-01-05 07:46

sed is a much better tool for the job: sed -n '/re/,$p' file

where re is regexp.

Another option is grep's --after-context flag. You need to pass in a number to end at, using wc on the file should give the right value to stop at. Combine this with -n and your match expression.

查看更多
Juvenile、少年°
7楼-- · 2019-01-05 07:47

There are many ways to do it with sed or awk:

sed -n '/TERMINATE/,$p' file

This looks for TERMINATE in your file and prints from that line up to the end of the file.

awk '/TERMINATE/,0' file

This is exactly the same behaviour as sed.

In case you know the number of the line from which you want to start printing, you can specify it together with NR (number of record, which eventually indicates the number of the line):

awk 'NR>=535' file

Example

$ seq 10 > a        #generate a file with one number per line, from 1 to 10
$ sed -n '/7/,$p' a
7
8
9
10
$ awk '/7/,0' a
7
8
9
10
$ awk 'NR>=7' a
7
8
9
10
查看更多
登录 后发表回答