Jump to content

Search in paragraph's text

From Rosetta Code
Task
Search in paragraph's text
You are encouraged to solve this task according to the task description, using any language you may know.

The goal is to verify the presence of a word or regular expression within several paragraphs of text (structured or not) and to format the output of the relevant paragraphs before putting them on the standard output.

So here, let’s imagine that we are trying to verify the presence of a keyword "SystemError" within what I want to call "the paragraphs" "Traceback (most recent call last):" in the file Traceback.txt

cat Traceback.txt :

2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py", line 99, in run
    result = plugin.run()
  File "/usr/lib/python3/dist-packages/landscape/sysinfo/processes.py", line 18, in run
    for process_info in info.get_all_process_info():
  File "/usr/lib/python3/dist-packages/landscape/lib/process.py", line 39, in get_all_process_info
    process_info = self.get_process_info(process_id)
  File "/usr/lib/python3/dist-packages/landscape/lib/process.py", line 61, in get_process_info
    cmd_line = file.readline()
  File "/usr/lib/python3.6/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 152: ordinal not in range(128)

2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.
Traceback (most recent call last):
    vmodl.fault.SystemError: (vmodl.fault.SystemError) {
    dynamicType = ,
    dynamicProperty = (vmodl.DynamicProperty) [],
    msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
    faultCause = ,
    faultMessage = (vmodl.LocalizableMessage) [],
    reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
    }

[Tue Jan 21 16:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.

[Tue Jan 21 17:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):
[Tue Jan 21 17:16:19.250679 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757]   File "/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi", line 5, in <module>
[Tue Jan 21 17:16:19.251735 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757]     from test import app as application
[Tue Jan 21 17:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] ImportError: cannot import name app

2021-04-23 17:13:14,425 ERROR    Network plugin raised an exception.
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py", line 99, 
in run
    result = plugin.run()
  File "/usr/lib/python3/dist-packages/landscape/sysinfo/network.py", line 36, 
in run
    device_info = self._get_device_info()
  File "/usr/lib/python3/dist-packages/landscape/lib/network.py", line 163, in 
get_active_device_info
    speed, duplex = get_network_interface_speed(
  File "/usr/lib/python3/dist-packages/landscape/lib/network.py", line 249, in 
get_network_interface_speed
    res = status_cmd.tostring()
AttributeError: 'array.array' object has no attribute 'tostring'

11/01 18:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| TypeError: 'NoneType' object is not iterable

12/01 19:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory

Traceback (most recent call last):
    File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
    WaitForTask(task)
    File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
    raise task.info.error
    vmodl.fault.SystemError: (vmodl.fault.SystemError) {
    dynamicType = ,
    dynamicProperty = (vmodl.DynamicProperty) [],
    msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
    faultCause = ,
    faultMessage = (vmodl.LocalizableMessage) [],
    reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
    }

The expected result must be formated with ---------------- for paragraph's separator AND "Traceback (most recent call last):" as the beginning of each relevant's paragraph :

Traceback (most recent call last):
    vmodl.fault.SystemError: (vmodl.fault.SystemError) {
    dynamicType = ,
    dynamicProperty = (vmodl.DynamicProperty) [],
    msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
    faultCause = ,
    faultMessage = (vmodl.LocalizableMessage) [],
    reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
    }
----------------
Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
----------------
Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
----------------
Traceback (most recent call last):
    File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
    WaitForTask(task)
    File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
    raise task.info.error
    vmodl.fault.SystemError: (vmodl.fault.SystemError) {
    dynamicType = ,
    dynamicProperty = (vmodl.DynamicProperty) [],
    msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
    faultCause = ,
    faultMessage = (vmodl.LocalizableMessage) [],
    reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
    }
----------------

11l

Translation of: Python
V f = File(‘Traceback.txt’)
V rawText = f.read()

V paragraphs = rawText.split("\n\n")

L(p) paragraphs
   I ‘SystemError’ C p

      V index = p.findi(‘Traceback (most recent call last):’)

      I -1 != index
         print(p[index ..])
         print(‘----------------’)

AutoHotkey

FileRead, fileContents, Traceback.txt
keyWord      := "SystemError"    ; or regex like "SystemE\w+"
beginWith    := "Traceback (most recent call last):"
for i, paragraph in StrSplit(StrReplace(fileContents, "`r"), "`n`n")
    result   .= RegExMatch(paragraph, keyWord) ? SubStr(paragraph, InStr(paragraph, beginWith, 1)) "`n----------------`n" : ""
MsgBox % result
Output:
Traceback (most recent call last):
    vmodl.fault.SystemError: (vmodl.fault.SystemError) {
    dynamicType = ,
    dynamicProperty = (vmodl.DynamicProperty) [],
    msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
    faultCause = ,
    faultMessage = (vmodl.LocalizableMessage) [],
    reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
    }
----------------
Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
----------------
Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
----------------
Traceback (most recent call last):
    File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
    WaitForTask(task)
    File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
    raise task.info.error
    vmodl.fault.SystemError: (vmodl.fault.SystemError) {
    dynamicType = ,
    dynamicProperty = (vmodl.DynamicProperty) [],
    msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
    faultCause = ,
    faultMessage = (vmodl.LocalizableMessage) [],
    reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
    }
----------------

AWK

Using the awk "Record Separator" :

awk 'BEGIN { RS = "" ; ORS = "\n----------------\n" } /Traceback/ && /SystemError/ { print substr($0,index($0,"Traceback")) }' Traceback.txt

Note : RS is modified from "\n" to "" in order to use Traceback information in index function.

ORS is modified to seperate the paragraphs with "\n----------------\n"

Each paragraph must contains "Traceback" and "SystemError"

substr is extracting only characters after "Traceback" appearance, until the next matching "Traceback" and "SystemError".

C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define INPUT_FILE_NAME     "Traceback.txt"
#define KEYWORD_STRING      "SystemError"
#define TRACEBACK_STRING    "Traceback (most recent call last):"
#define END_OF_PARAGRAPH    "\n----------------\n"

char *load_paragraph( FILE *f );

int main() {
    FILE *f   = fopen( INPUT_FILE_NAME, "r" );

    if( f ) {
        char *par = NULL;

        while( (par=load_paragraph(f)) ) {
            if( strstr(par,KEYWORD_STRING) ) {
                char *p = strstr( par, TRACEBACK_STRING );

                if( p ) printf( p );
                else printf( "%s\n%s", TRACEBACK_STRING, par );

                printf( END_OF_PARAGRAPH );
            }

            free( par ); par = NULL;
        }

        if( !feof(f) )
            puts( "End of file not reached." );

        fclose( f ); f = NULL;
    }
    else {
        puts( "Input file not opened." );
    }

    return 0;
}

/*===========================================================================
Starting from the current position, looks for the first occurrence of "\n\n"
in the file f, counting the number of characters from the current position
to "\n\n" itself (not included) or to the end of the file (whichever occurs
first). Resets the file to its original position, then returns the number of
characters.
If the funtions fails, it returns ((size_t)-1).
===========================================================================*/

size_t get_paragraph_length( FILE *f ) {
    size_t l = ((size_t)-1);

    if( f && !feof(f) ) {
        fpos_t ex_pos;

        if( 0==fgetpos(f,&ex_pos) ) {
            int c;

            for( c=fgetc(f); c!=EOF; c=fgetc(f) ) {
                if( '\n'==c ) {
                    if( '\n'!=(c=fgetc(f)) ) {
                        ungetc( c, f );
                    }
                    else {
                        ++l;
                        break;
                    }
                }

                ++l;
            }

            l += EOF==c;

            fsetpos( f, &ex_pos );
        }
    }

    return l;
}

/*===========================================================================
Loads a paragraph from the file f. Paragraphs are detected looking for the
occurrences of "\n\n" separators. The loaded paragraph is put into a chunk of
memory allocated with malloc(). The pointer to that memory is returned.
If the function fails, no memory is allocated and NULL is returned.
===========================================================================*/

char *load_paragraph( FILE *f ) {
    char *par = NULL;

    if( !feof(f) ) {
        size_t i, l = get_paragraph_length( f );

        if( ((size_t)-1)!=l ) {
            par = malloc( l+1 );

            if( par ) {
                for( i=0; i<l; ++i )
                    par[i] = fgetc( f );
                par[i] = '\0';

                /* just jump beyond the paragraph delimiter */
                fgetc( f ); fgetc( f );
            }
        }
    }

    return par;
}
Output:
Output as required by task.

C++

#include <algorithm>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

const std::string PARAGRAPH_SEPARATOR = "\n\n";

int main() {
	std::ifstream file;
	file.open("../Traceback.txt");
	std::stringstream stream;
	stream << file.rdbuf();
	std::string file_contents = stream.str();

	std::vector<std::string> paragraphs;
	uint64_t start;
	uint64_t end = 0;
	while ( ( start = file_contents.find_first_not_of(PARAGRAPH_SEPARATOR, end) ) != std::string::npos ) {
		end = file_contents.find(PARAGRAPH_SEPARATOR, start);
		paragraphs.emplace_back(file_contents.substr(start, end - start));
	}

	for ( const std::string& paragraph : paragraphs ) {
		if ( paragraph.find("SystemError") != std::string::npos ) {
			int32_t index = paragraph.find("Traceback (most recent call last):");
			if ( index >= 0 ) {
				std::cout << paragraph.substr(index) << std::endl;
				std::cout << "----------------" << std::endl;
			}
		}
	}
}
Output:
Output as required by task.

FreeBASIC

Translation of: Python
Function ReadFile(filename As String) As String
    Dim As String content = ""
    Dim As String linea
    
    Dim As Integer ff = Freefile
    If Open(filename For Input As #ff) = 0 Then
        While Not Eof(ff)
            Line Input #ff, linea
            content &= linea & Chr(10)
        Wend
        Close #ff
    Else
        Print "Error opening file: " & filename
    End If
    
    Return content
End Function

Sub SplitString(text As String, delimiter As String, arr() As String)
    Dim As Integer posic, cnt = 0, start = 1
    
    Do
        posic = Instr(start, text, delimiter)
        If posic = 0 Then posic = Len(text) + 1
        
        cnt += 1
        Redim Preserve arr(1 To cnt)
        arr(cnt) = Mid(text, start, posic - start)
        
        start = posic + Len(delimiter)
    Loop Until start > Len(text)
End Sub

Dim As String rawText = ReadFile("Traceback.txt")
Dim paragraphs() As String
SplitString(rawText, Chr(10) & Chr(10), paragraphs())

For i As Integer = 1 To Ubound(paragraphs)
    Dim As String p = paragraphs(i)
    
    If Instr(p, "SystemError") > 0 Then
        Dim As Integer index = Instr(p, "Traceback (most recent call last):")
        
        If index <> 0 Then
            Print Mid(p, index)
            Print "----------------"
        End If
    End If
Next i

Sleep
Output:
Traceback (most recent call last):
    vmodl.fault.SystemError: (vmodl.fault.SystemError) {
    dynamicType = ,
    dynamicProperty = (vmodl.DynamicProperty) [],
    msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
    faultCause = ,
    faultMessage = (vmodl.LocalizableMessage) [],
    reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
    }
----------------
Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
----------------
Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
----------------
Traceback (most recent call last):
    File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
    WaitForTask(task)
    File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
    raise task.info.error
    vmodl.fault.SystemError: (vmodl.fault.SystemError) {
    dynamicType = ,
    dynamicProperty = (vmodl.DynamicProperty) [],
    msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
    faultCause = ,
    faultMessage = (vmodl.LocalizableMessage) [],
    reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
    }

----------------

J

Implementation:

NB. read file, separate on blank lines
paragraphs=: ((LF,LF)&E. <;.2 ])fread 'traceback.txt'

NB. ignore text preceding 'Traceback (most recent call last)'
cleaned=:  {{y}.~{.I.'Traceback (most recent call last)'&E.y}}each paragraphs

NB. limit to paragraphs containing 'SystemError'
searched=: (#~ (1 e.'SystemError'&E.)every) cleaned

NB. add "paragraph 'separator'" and display
echo ;searched ,L:0 '----------------',LF
Output:
Traceback (most recent call last):
    vmodl.fault.SystemError: (vmodl.fault.SystemError) {
    dynamicType = ,
    dynamicProperty = (vmodl.DynamicProperty) [],
    msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
    faultCause = ,
    faultMessage = (vmodl.LocalizableMessage) [],
    reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
    }
----------------
Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
----------------
Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:...
----------------
Traceback (most recent call last):
    File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
    WaitForTask(task)
    File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
    raise task.info.error
    vmodl.fault.SystemError: (vmodl.fault.SystemError) {
    dynamicType = ,
    dynamicProperty = (vmodl.DynamicProperty) [],
    msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
    faultCause = ,
    faultMessage = (vmodl.LocalizableMessage) [],
    reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
    }
----------------

Java

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public final class SearchInParagraphsText {

	public static void main(String[] args) throws IOException {	
		Path filePath = Path.of("./Traceback.txt");
		String fileContents = Files.readString(filePath, StandardCharsets.UTF_8);
	    String[] paragraphs = fileContents.split(PARAGRAPH_SEPARATOR);
	    for ( String paragraph : paragraphs ) {
	    	if ( paragraph.contains("SystemError") ) {
	    		int index = paragraph.indexOf("Traceback (most recent call last):");
	    		if ( index >= 0 ) {
	            	System.out.println(paragraph.substring(index));
	            	System.out.println("----------------");
	            }
    		}
	    }
	}
	
	private static final String PARAGRAPH_SEPARATOR = "\r\n\r\n";

}
Output:
Output as requested by task

jq

Works with: jq

Works with gojq, the Go implementation of jq

def p1: "Traceback (most recent call last):";
def p2: "SystemError";
def sep: "----------------";
 
split("\n\n")[]
| index(p1) as $ix
| select( $ix and index(p2) )
| .[$ix:], sep

Invocation:

   jq -rRs -f program.jq Traceback.txt
Output:

As required.

Julia

const filename = "traceback.txt"
const pmarker, target = "Traceback (most recent call last):", "SystemError"

foreach(
    p -> println(p, p[end] == '\n' ? "" : "\n", "-"^16),
    [
        p[findfirst(pmarker, p).start:end] for
        p in split(read(filename, String), r"\r?\n\r?\n") if
        contains(p, pmarker) && contains(p, target)
    ],
)

Nim

Translation of: Python
import std/strutils

let rawText = readFile("Traceback.txt")

for paragraph in rawText.split("\n\n"):
  if "SystemError" in paragraph:
    let index = paragraph.find("Traceback (most recent call last):")
    if index != -1:
      echo paragraph[index..^1]
      echo "----------------"

Perl

Translation of: AWK
use strict;
use warnings;

local $/ = "";  # Set the input record separator to an empty string to read paragraph mode
local $\ = "\n----------------\n";  # Set the output record separator

# Open the file Traceback.txt for reading
open my $fh, '<', 'Traceback.txt' or die "Cannot open Traceback.txt: $!";

# Read one paragraph at a time
while (<$fh>) {
    if (/Traceback \(most recent call last\):/ && /SystemError/) {
        print substr($_, index($_, "Traceback (most recent call last):"));
    }
}

Phix

with javascript_semantics
--constant text = get_text("Traceback.txt") -- (not js!)
constant text = """
2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.
<snip>
    }""",
paras = split(text,"\n\n"),
tmrcl = "Traceback (most recent call last)"
for i=1 to length(paras) do
    string para = paras[i]
    integer tdx = match(tmrcl,para)
    if tdx then
        para = para[tdx..$]
        if match("SystemError",para) then
            printf(1,"%s\n----------------\n",{para})
        end if
    end if
end for

Output as requested

Phixmonti

include ..\Utilitys.pmt

"Traceback (most recent call last):" >ps
""

"Traceback.txt" "r" fopen >ps

tps 0 > while
	tps fgets
	number? if drop false else chain true endif
endwhile

ps> fclose

"\n\n" xplit

len for
	get
	"SystemError" find
	if
		tps find dup
		if
			snip ? "----------------" ? drop
		else
			drop tps ? ? "----------------" ?
		endif
	else
		drop
	endif
endfor
cps
Output:
Traceback (most recent call last):
    vmodl.fault.SystemError: (vmodl.fault.SystemError) {
    dynamicType = ,
    dynamicProperty = (vmodl.DynamicProperty) [],
    msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
    faultCause = ,
    faultMessage = (vmodl.LocalizableMessage) [],
    reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
    }
----------------
Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
----------------
Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
----------------
Traceback (most recent call last):
    File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
    WaitForTask(task)
    File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
    raise task.info.error
    vmodl.fault.SystemError: (vmodl.fault.SystemError) {
    dynamicType = ,
    dynamicProperty = (vmodl.DynamicProperty) [],
    msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
    faultCause = ,
    faultMessage = (vmodl.LocalizableMessage) [],
    reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
    }
----------------

=== Press any key to exit ===

Python

with open('Traceback.txt', 'r' ) as f:
    rawText = f.read()

paragraphs = rawText.split( "\n\n" )

for p in paragraphs:
    if "SystemError" in p:

        index = p.find( "Traceback (most recent call last):" )

        if -1 != index:
            print( p[index:] )
            print( "----------------" )

Output as requested.

Raku

Generalized. Pipe in the file from the shell, user definable search term and entry point.

unit sub MAIN ( :$for, :$at = 0 );

put slurp.split( /\n\n+/ ).grep( { .contains: $for } )
         .map( { .substr: .index: $at } )
         .join: "\n----------------\n"
Example output using command line:
   raku search.raku --for='SystemError' --at='Traceback' < traceback.txt

Matches expected except for not having a extraneous trailing paragraph separator.

Traceback (most recent call last):
    vmodl.fault.SystemError: (vmodl.fault.SystemError) {
    dynamicType = ,
    dynamicProperty = (vmodl.DynamicProperty) [],
    msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
    faultCause = ,
    faultMessage = (vmodl.LocalizableMessage) [],
    reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
    }
----------------
Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
----------------
Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
----------------
Traceback (most recent call last):
    File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
    WaitForTask(task)
    File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
    raise task.info.error
    vmodl.fault.SystemError: (vmodl.fault.SystemError) {
    dynamicType = ,
    dynamicProperty = (vmodl.DynamicProperty) [],
    msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
    faultCause = ,
    faultMessage = (vmodl.LocalizableMessage) [],
    reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
    }

sed

/./{
H
$!d
}
x
:l
/^Traceback (most recent call last):/!s/^.[^T]*//
t l
/SystemError/!d
a\
----------------

Output as requested by task.

Wren

Library: Wren-pattern
import "io" for File
import "./pattern" for Pattern

var fileName = "Traceback.txt"
var p1 = Pattern.new("Traceback (most recent call last):")
var p2 = Pattern.new("SystemError")
var sep = "----------------"

File.read(fileName)
    .split("\n\n")
    .where { |para| p1.isMatch(para) && p2.isMatch(para) }
    .each { |para|
        var ix = p1.find(para).index
        System.print(para[ix..-1])
        System.print(sep)
    }
Output:
Traceback (most recent call last):
    vmodl.fault.SystemError: (vmodl.fault.SystemError) {
    dynamicType = ,
    dynamicProperty = (vmodl.DynamicProperty) [],
    msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
    faultCause = ,
    faultMessage = (vmodl.LocalizableMessage) [],
    reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
    }
----------------
Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
----------------
Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
----------------
Traceback (most recent call last):
    File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
    WaitForTask(task)
    File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
    raise task.info.error
    vmodl.fault.SystemError: (vmodl.fault.SystemError) {
    dynamicType = ,
    dynamicProperty = (vmodl.DynamicProperty) [],
    msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
    faultCause = ,
    faultMessage = (vmodl.LocalizableMessage) [],
    reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
    }
----------------
Cookies help us deliver our services. By using our services, you agree to our use of cookies.