Is there a way to map such a pattern to a shell or sed?

I have a file with the following output:

BP 0 test: case id Name ====== ======== ================= 0 82 a_case-2-0-0 BP 1 test: case id Name ====== ======== ================= 0 86 a_case-2-1-0 BP 2 test: case id Name ====== ======== ================= BP 3 test: case id Name ====== ======== ================= 0 93 a_case-2-3-0 

therefore, only "BP 0,1,3" have content, so I want to be able to reset "BP test 0", "BP test 1" and "BP 3 test", just want to delay the test "BP 2" ​​because lack of test.

Thanks for your help.

+6
source share
4 answers
 $ awk -F'\n' -v RS='' -v ORS='\n\n' 'NF>3' input.txt BP 0 test: case id Name ====== ======== ================= 0 82 a_case-2-0-0 BP 1 test: case id Name ====== ======== ================= 0 86 a_case-2-1-0 BP 3 test: case id Name ====== ======== ================= 0 93 a_case-2-3-0 
+3
source

While you can hit something using smaller shell tools like [ and expr , this will be easier to do with awk , which you usually find on any operating system that also includes grep and sed . :)

It's quick and dirty here:

 [ ghoti@pc ~]$ cat doit #!/usr/bin/awk -f /^BP/ { output=$0; getline; output=sprintf("%s\n%s", output, $0); getline; output=sprintf("%s\n%s", output, $0); getline; if (/[0-9]/) { output=sprintf("%s\n%s\n", output, $0); print output; } } [ ghoti@pc ~]$ ./doit input.txt BP 0 test: case id Name ====== ======== ================= 0 82 a_case-2-0-0 BP 1 test: case id Name ====== ======== ================= 0 86 a_case-2-1-0 BP 3 test: case id Name ====== ======== ================= 0 93 a_case-2-3-0 [ ghoti@pc ~]$ 

Please note that this script accepts some information about your input. If the conditions in the if do not work for you, or if there is the possibility of several cases after one test, this script will need to be adjusted.

+3
source

If your grep supports the -B option, you can do it like this:

 grep -B3 "_case-" <ip_file> | grep "BP " 

Conclusion for the above

 BP 0 test: BP 1 test: BP 3 test: 

Here -B3 prints 3 lines above the matching pattern.

+2
source

This might work for you:

 sed 'N;N;N;$!N;/\n\n$/d' file 
0
source

Source: https://habr.com/ru/post/912997/


All Articles