Operating System - HP-UX
1752591 Members
3353 Online
108788 Solutions
New Discussion юеВ

Re: grep for a string and redirect all lines after that occurence to another file

 
Must123
Occasional Advisor

grep for a string and redirect all lines after that occurence to another file

Hi,

I have a problem. I need to find a particular string in a file and display all lines coming after the occurence of the string.

Is that possible and how?

Thanks in advance,
Goutham
5 REPLIES 5
James R. Ferguson
Acclaimed Contributor

Re: grep for a string and redirect all lines after that occurence to another file

Hi Goutham:

This can easily be done in 'awk' or Perl. By example we could look for the string "local" in an '/etc/hosts':

# awk '/local/ {X=1};{if (X) {print}}' /etc/hosts

In Perl we can do the same and add case-insensitive matching like:

# perl -ne '/LoCaL/i and $X=1;print if $X' /etc/hosts

Regards!

...JRF...
Dennis Handly
Acclaimed Contributor

Re: grep for a string and redirect all lines after that occurence to another file

You can also use sed:
sed -n -e '/string/,$p' file > file2
(This includes the line with "string".)
James R. Ferguson
Acclaimed Contributor

Re: grep for a string and redirect all lines after that occurence to another file

Hi (again):

If you want to _exclude_ the line with the matching string, but print every line beyond to the file's end, you could do:

# perl -ne '/LoCaL/i and {$x=1,next};print if $x' /etc/hosts

This case-insensitively matches the string "local"; skips printing that line; and prints every line to the file's end.

As always, if you want to redirect the output from your terminal to a file, simply do:

# perl -ne '/LoCaL/i and {$x=1,next};print if $x' /etc/hosts > /tmp/myoutput

Analogous to 'sed' or 'awk', Perl offers another way to match a pattern and print from the line with the pattern to the end of a file:

# perl -ne 'print if /LoCaL/i..eof' /etc/hosts > /tmp/myoutput

Regards!

...JRF...
Must123
Occasional Advisor

Re: grep for a string and redirect all lines after that occurence to another file

Thanks a lot James annd Dennis for your help.

Regards,
Goutham
Must123
Occasional Advisor

Re: grep for a string and redirect all lines after that occurence to another file

.