Reputation: 45
What I need is:
I need to delete the entire line but need to keep the matching strings.
matching pattern starting with Unhandled
and ending with a :
I tried the below code which prints the matching pattern, but I need to delete the extra lines from the file.
perl -0777 -ne 'print "Unhandled error at$1\n" while /Unhandled\ error\ at(.*?):/gs' filename
Below is the sample input:
2012-04-09 01:52:13,717 - uhrerror - ERROR - 22866 - /home/shabbir/web/middleware.py process_exception - 217 - Unhandled error at /user/resetpassword/: : {'mod_wsgi.listener_port': '8080', 'HTTP_COOKIE': "__utma=1.627673239.1309689718.1333823126.1333916263.156; __utmz=1.1333636950.152.101.utmgclid=CMmkz934na8CFY4c6wod_R8JbA|utmccn=(not%20set)|utmcmd=(not%20set)|utmctr=non-stick%20kadai%20online; subpopdd=yes; _msuuid_1690zlm11992=FCC09820-3004-413A-97A3-1088EE128CE9; _we_wk_ls_=%7Btime%3A'1322900804422'%7D; _msuuid_lf2uu38ua0=08D1CEFE-3C19-4B9E-8096-240B92BA0ADD; nevermissadeal=True; sessionid=c1e850e2e7db09e98a02415fc1ef490; __utmc=1; __utmb=1.7.10.1333916263; 'wsgi.file_wrapper': , 'HTTP_ACCEPT_ENCODING': 'gzip, deflate'}
Upvotes: 3
Views: 500
Reputation:
perl -0777 -i -pe 's/.*?(Unhandled error .*?):.*/$1/g' filename
This will replace error block with matched string in the file.
-0777
: will force Perl to read the whole file in one shot.
-i
: means in-place editing of files.
-p
: means loop line-by-line through contents of file,execute code in single quotes i.e.'s/.*?(Unhandled error .*?):.*/$1/g'
,and print the result(matched string),which is written back to file using -i
option.
-e
: for command-line
Upvotes: 0
Reputation: 67900
I would use -l
option to handle line endings (less version dependent, prints a new line for each match), and a for
loop to print all the matches, not just the first one $1
. No need to slurp the file with -0777
.
perl -nwle 'print for /Unhandled error at .*?:/g'
Note that with the /g
modifier, a capturing parenthesis is not required.
If only one (the first) match is to be printed, /g
is redundant and you can just use $1
:
perl -nlwe 'print $1 if /(Unhandled error at .*?):/'
Upvotes: 0
Reputation: 385590
The code you gave already provides the requested behaviour.
That said, there's a huge redundant string in your program you can eliminate.
perl -0777nE'say $1 while /(Unhandled error at .*?):/gs' filename
Finally, slurping the entire file seems entirely superfluous.
perl -nE'say $1 if /(Unhandled error at .*?):/g' filename
Upvotes: 1
Reputation: 2191
If one match is all you want to keep from the whole string, you could replace the string value with the match afterwards. (i.e. Simply assign the new value)
If you have several matches within the string, the least complicated method may be to store the matches temporarily in an array. Then just discard the original variable if you don't need it anymore.
Upvotes: 0