![]() |
Hello and Welcome from United States to the UNIX and Linux Forums! Thank You for Visiting and Joining Our Global Community.
|
|
google unix.com
|
|||||||
| Forums | Register | Forum Rules | Links | Albums | FAQ | Members List | 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. |
More UNIX and Linux Forum Topics You Might Find Helpful
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| counting the lines matching a pattern, in between two pattern, and generate a tab | d.chauliac | Shell Programming and Scripting | 4 | 03-19-2009 01:30 PM |
| Pattern Matching | Siv_Pat | Shell Programming and Scripting | 6 | 01-12-2009 04:46 AM |
| comment/delete a particular pattern starting from second line of the matching pattern | imas | Shell Programming and Scripting | 4 | 10-13-2008 03:37 AM |
| pattern matching | malle | Shell Programming and Scripting | 3 | 01-31-2007 05:23 AM |
| pattern matching | larryase | UNIX for Dummies Questions & Answers | 3 | 11-22-2004 06:54 PM |
![]() |
|
|
LinkBack | Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
||||
|
multiline pattern matching
Hi,
I have a file of the following from: Afghanistan gdpcapit|800 Akrotiri Albania gdpcapit|6000 now I want have the gdpcapit value next to the country when there is one like this: Afghanistan 800 gdpcapit|800 Akrotiri Albania 6000 gdpcapit|6000 How do I do this? I've been searching for this all day... On the machine i'm working on there is no grep that supports -B or -A... there should be a gawk or gsed though thanks in advance |
|
||||
|
if you have Python, here's an alternative solution
Code:
o=0
data=open("file").readlines()
data=[i.strip() for i in data]
for n,line in enumerate(data):
line=line.strip()
if line.startswith("gdpcapit"):
number=line.split("|")[-1]
for i in data[o:n]:
print "%s %d"%(i,int(number))
print line
o=n+1
Code:
# ./test.py Afghanistan 800 gdpcapit|800 Akrotiri 6000 Albania 6000 gdpcapit|6000 |
|
||||
|
if your file is in small size, below perl code should work for you.
if it is a huge size file, may need to resort to other solution ![]() Code:
my @tmp=<DATA>;
map {s/\n//} @tmp;
my @arr=reverse @tmp;
for (my $i=1;$i<=$#arr;$i++){
if($arr[$i-1] =~ /gdpcapit\|/ && $arr[$i] !~ /\|/){
my @t=split("[|]",$arr[$i-1]);
$arr[$i].=" ".$t[1]
}
}
map {print $_,"\n"} reverse @arr;
__END__
Afghanistan
gdpcapit|800
Akrotiri
Albania
gdpcapit|6000
|
![]() |
| Bookmarks |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|