It is necessary to delete the entire line except the corresponding lines

What I need:
I need to delete the entire line, but need to keep the corresponding lines.

starting with and ending with Unhandled

:

I tried the below code which prints the appropriate pattern, but I need to remove additional lines from the file.

perl -0777 -ne 'print "Unhandled error at$1\n" while /Unhandled\ error\ at(.*?):/gs' filename

      

Below is an example of input:

2012-04-09 01: 52: 13,717 - uhrerror - ERROR - 22866 - / home / shabbir / web / middleware.py process_exception - 217 - Unhandled error on / 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 = 20cm% 20mccn) | (notr% 20mccn) ; 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'}

+3


source to share


4 answers


perl -0777 -i -pe 's/.*?(Unhandled error .*?):.*/$1/g' filename

      

This will replace the error block with the matching line in the file.



-0777

: makes Perl read the entire file in one snapshot. : means editing files in place. : means loop through the lines through the contents of the file, execute the code in single quotes, i.e. , and print the result (the matching string), which is written back to the file with . : for command line
-i


-p

's/.*?(Unhandled error .*?):.*/$1/g'

-i


-e

0


source


The code you provided already provides the requested behavior.

However, there is a huge redundant line in your program.

perl -0777nE'say $1 while /(Unhandled error at .*?):/gs' filename

      



Finally, clipping the entire file seems completely redundant.

perl -nE'say $1 if /(Unhandled error at .*?):/g' filename

      

+1


source


If one match is all you want to keep from the entire string, you can replace the string value with the match. (i.e. just assign a new value)

If there are multiple matches in the string, the least difficult method might be to temporarily store the matches in an array. Then just drop the original variable if you don't need it anymore.

0


source


I would use a parameter -l

to handle line endings (less version dependent, prints a newline for each match) and a loop for

to print all matches, not just the first one $1

. There is no need to cut the file with -0777

.

perl -nwle 'print for /Unhandled error at .*?:/g'

      

Note that you /g

don't need to copy the parentheses with the modifier .

If only one (first) match should be printed, it /g

is redundant and you can simply use $1

:

perl -nlwe 'print $1 if /(Unhandled error at .*?):/'

      

0


source







All Articles