|
|||||||
| Forums | Search Forums | Register | Forum Rules | Man Pages | Albums | FAQ | Members | Calendar | Search | Today's Posts | Mark Forums Read |
| Shell Programming and Scripting Post questions about KSH, CSH, SH, BASH, PERL, PHP, SED, AWK and OTHER shell scripts and shell scripting languages here. |
|
|
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Read text between two lines containing a string
Hi, I have text file like the following: Code:
Start a b 121 c d End Start a 31 e f End Start p o i k l 993 End Now I want to output the Start-End block that contains my search string So if I search for '121' it should output the first block, search for 'k' then output the last block Thanks, -sri |
| Sponsored Links | ||
|
|
#2
|
||||
|
||||
|
Code:
awk -v V="121" ' /Start/ {
s=x;
s=$0;
} !/Start/&&!/End/ {
s=s RS $0;
} $0 == V {
f = 1;
} /End/ && f == 1 {
s=s RS $0;
print s;
f = 0;
}' file |
| Sponsored Links | ||
|
|
#3
|
|||
|
|||
|
Got the solution Code:
awk '/Start/{s=x}{s=s$0"\n"}/121/{p=1}/End/ && p{print s;exit}' <filename> |
|
#4
|
||||
|
||||
|
Converting it each section to rows, simplify handling it. Code:
awk '{if ($0~"End") {print $0"\n"} else {print $0","}}' ORS="" | awk '/k/'
Start,p,o,i,k,l,993,End |
| Sponsored Links | |
|
|
#5
|
||||
|
||||
|
Note that this program will not print another section if the search pattern is repeated. But if that is what you want, then it is OK.
|
| Sponsored Links | |
|
|
#6
|
|||
|
|||
|
Hi bipinajith, the search string will not appear in multiple blocks, thanks for thinking about this.
After I posted my question I found solution based on the following link (credit goes to this): http://www.unix.com/shell-programmin...o-strings.html |
| Sponsored Links | ||
|
![]() |
| Thread Tools | Search this Thread |
| Display Modes | |
More UNIX and Linux Forum Topics You Might Find Helpful
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Read all lines after a string appears in the file. | Nagaraja Akkiva | Shell Programming and Scripting | 4 | 10-24-2011 07:57 AM |
| Print lines between two lines after grep for a text string | jbruce | Shell Programming and Scripting | 7 | 09-29-2010 02:37 PM |
| Shell script to read lines in a text file and filter user data | srimal | Shell Programming and Scripting | 4 | 10-23-2009 01:35 AM |
| Read any lines of text from file | versace | Shell Programming and Scripting | 6 | 10-20-2009 02:34 AM |
| Read text file from a specified string to the end | bsrajirs | UNIX for Advanced & Expert Users | 9 | 01-11-2008 12:05 AM |
|
|