muay_tb
November 19, 2009, 9:59am
1
Hi all,
I was wondering if someone could tell me a way to extract from a file lines where you search for a phrase and then also extract the next X lines after it (i.e. take a block of text from the file)?
Example
{
id=123
time=10:00:00
date=12/12/09
{
........
}
}
{
id=123
time=10:00:00
date=12/12/09
{
........
}
}
If possible i want to extract the id, time and date block....
Also is there a way also to extract text between 2 tags? such as { and } in my example?
danmero
November 19, 2009, 10:36am
2
You can use grep -Ax if your grep support this option, awk or sed shell script, etc...
The answer and the solution depend on your required output.
muay_tb
November 19, 2009, 11:13am
3
Unfortunately I do not have the grep -A option as I am on older systems.
All i want is to extract the information, at this stage no formatting is required so:
id=123
time=10:00:00
date=12/12/09
<SPACE>
id=123
time=11:00:00
date=12/12/09
....
danmero
November 19, 2009, 12:05pm
4
Try
awk '/id/{f=1}/date/{print $0 ORS;f=0}f' FILE
thegeek
November 19, 2009, 12:33pm
5
Print id, and 2 lines following it.
sed -n '/id/,+2p' FILE
sed -n : suppress default print,
/id/ : match pattern 'id'
+2 : next 2 lines
p: print
print from { to }
sed -n '/{/,/}/p' FILE
sed -n : suppress default print,
/{/,/}/ : match from { to }
p : print
But the 2nd one will print everything, as all your text is enclosed with { and }
danmero
November 19, 2009, 1:00pm
6
thegeek:
Print id, and 2 lines following it.
sed -n '/id/,+2p' FILE
This is the similar to
awk '/id/,/date/' FILE
however your solution don't insert blank line between record blocks :rolleyes: see OP requirement.
thegeek
November 20, 2009, 12:07am
7
sed -n '/id/{p;n;p;n;G;p}' t1
This can print the 2 lines from id, and with blank line following as asked for...
But, giving two regex /id/,/date/ cannot satisfy OPs requirement as printing next X lines, if date comes before/after 2 lines...