use awk to print after/before n lines after match

Gerrit提交总报错?手把手教你搞定Git的Missing Change-id问题(附commit-msg脚本) 本文详细解析Gerrit提交时常见的Missing Change-id报错问题,提供从commit-msg脚本获取到历史提交修复的完整解决方案。通过三种可靠方式获取hook脚本,并针对不同场景给出具体操作步骤,帮助开发者彻底解决Git与Gerrit集成中的这一典型问题。 阅读详情
sed -n '1,/Copying/p' bldlinux.log | tail -3

x=`awk '/Copying/{print NR-2","NR}' bldlinux.log `
sed -n "$x p" bldlinux.log


awk '{a[++i]=$0;}/Copying/{for(j=NR-2;j<=NR;j++)print a[j];}' bldlinux.log


In this article, we will discuss the  different ways for how to print a few lines before a pattern match in log files. You will do well to know how to print a few lines AFTER a pattern match.

 Let us consider a sample file as below. The requirement is to print 2 lines before the pattern 'Linux':
$ cat file
Unix
AIX
Solaris
Linux
SCO
1. grep will do it for you if your grep is a GNU grep.
$ grep -B2 Linux file
AIX
Solaris
Linux
The option '-B' will give n lines before the pattern. Hence '-B2 Linux' gives 2 lines before the pattern 'Linux' including the line matching the pattern.

2. awk way:
$ awk '/Linux/{for(i=1;i<=x;)print a[i++];print}
>             {for(i=1;i<x;i++)a[i]=a[i+1];a[x]=$0;}'  x=2 file
AIX
Solaris
Linux
 In this, an array is used which will always contain 2 lines before the current pattern. Hence, when the pattern is matched, the array contents along with the current pattern is printed.

3. Perl way:
$ perl -ne 'push @arr,$_; shift @arr if(@arr>3);
>          /Linux/ and print @arr;' file
AIX
Solaris
Linux
On reading a line, the line is pushed into an array named "arr". As and when the array size goes beyond 3, an element is removed from the front. In this way, the array will always contain 3 lines including the current pattern. On encountering the pattern 'Linux', the array is printed.

4. sed and tail combination:
$ sed -n '1,/Linux/p' file | tail -3
AIX
Solaris
Linux
Using sed, a range of lines can be read. sed reads from 1st line till the pattern 'Linux'. From this result, we print the last 3 lines which is nothing but the line containing the pattern and 2 lines before the pattern.

5. awk and sed combination:
$ x=`awk '/Linux/{print NR-2","NR}' file`
$ sed -n "$x p" file
AIX
Solaris
Linux
  Using awk, the line number range is retrieved using the pattern 'Linux'. NR gives the current line number which is the number of the line containing the pattern, NR-2 gives the gives the number of the line which is 2 lines before. Using this line range in sed, the set of lines can be filtered.

6. Another awk way, only if the file is a small one:
$ awk '{a[++i]=$0;}/Linux/{for(j=NR-2;j<=NR;j++)print a[j];}' file
AIX
Solaris
Linux
 In this, awk stores the entire file in memory using an array. On encountering the pattern 'Linux', it starts printing from 2 lines before using the for loop. Since awk stores the entire file in memory, this SHOULD not be used in case of large files since it will cause performance issues.

7. tac command (The least favored option)
$ tac file | grep -A2 Linux | tac
AIX
Solaris
Linux
tac command is reverse of cat command which prints the file in reverse order. On the reversed file, grep for 2 lines above the pattern, and again reverse the output and display. This is just an option, not the preferred one due to its performance. tac command itself is not good for performance, add to that, using it twice.
 Note: tac command is not available in all flavors of Unix. - See more at: http://www.theunixschool.com/2012/08/print-lines-before-pattern-linux.html#sthash.hDKNCoh7.dpuf
In this article, we will discuss the  different ways for how to print a few lines before a pattern match in log files. You will do well to know how to print a few lines AFTER a pattern match.

 Let us consider a sample file as below. The requirement is to print 2 lines before the pattern 'Linux':
$ cat file
Unix
AIX
Solaris
Linux
SCO
1. grep will do it for you if your grep is a GNU grep.
$ grep -B2 Linux file
AIX
Solaris
Linux
The option '-B' will give n lines before the pattern. Hence '-B2 Linux' gives 2 lines before the pattern 'Linux' including the line matching the pattern.

2. awk way:
$ awk '/Linux/{for(i=1;i<=x;)print a[i++];print}
>             {for(i=1;i<x;i++)a[i]=a[i+1];a[x]=$0;}'  x=2 file
AIX
Solaris
Linux
 In this, an array is used which will always contain 2 lines before the current pattern. Hence, when the pattern is matched, the array contents along with the current pattern is printed.

3. Perl way:
$ perl -ne 'push @arr,$_; shift @arr if(@arr>3);
>          /Linux/ and print @arr;' file
AIX
Solaris
Linux
On reading a line, the line is pushed into an array named "arr". As and when the array size goes beyond 3, an element is removed from the front. In this way, the array will always contain 3 lines including the current pattern. On encountering the pattern 'Linux', the array is printed.

4. sed and tail combination:
$ sed -n '1,/Linux/p' file | tail -3
AIX
Solaris
Linux
Using sed, a range of lines can be read. sed reads from 1st line till the pattern 'Linux'. From this result, we print the last 3 lines which is nothing but the line containing the pattern and 2 lines before the pattern.

5. awk and sed combination:
$ x=`awk '/Linux/{print NR-2","NR}' file`
$ sed -n "$x p" file
AIX
Solaris
Linux
  Using awk, the line number range is retrieved using the pattern 'Linux'. NR gives the current line number which is the number of the line containing the pattern, NR-2 gives the gives the number of the line which is 2 lines before. Using this line range in sed, the set of lines can be filtered.

6. Another awk way, only if the file is a small one:
$ awk '{a[++i]=$0;}/Linux/{for(j=NR-2;j<=NR;j++)print a[j];}' file
AIX
Solaris
Linux
 In this, awk stores the entire file in memory using an array. On encountering the pattern 'Linux', it starts printing from 2 lines before using the for loop. Since awk stores the entire file in memory, this SHOULD not be used in case of large files since it will cause performance issues.

7. tac command (The least favored option)
$ tac file | grep -A2 Linux | tac
AIX
Solaris
Linux
tac command is reverse of cat command which prints the file in reverse order. On the reversed file, grep for 2 lines above the pattern, and again reverse the output and display. This is just an option, not the preferred one due to its performance. tac command itself is not good for performance, add to that, using it twice.
 Note: tac command is not available in all flavors of Unix. - See more at: http://www.theunixschool.com/2012/08/print-lines-before-pattern-linux.html#sthash.hDKNCoh7.dpuf
In this article, we will discuss the  different ways for how to print a few lines before a pattern match in log files. You will do well to know how to print a few lines AFTER a pattern match.

 Let us consider a sample file as below. The requirement is to print 2 lines before the pattern 'Linux':
$ cat file
Unix
AIX
Solaris
Linux
SCO
1. grep will do it for you if your grep is a GNU grep.
$ grep -B2 Linux file
AIX
Solaris
Linux
The option '-B' will give n lines before the pattern. Hence '-B2 Linux' gives 2 lines before the pattern 'Linux' including the line matching the pattern.

2. awk way:
$ awk '/Linux/{for(i=1;i<=x;)print a[i++];print}
>             {for(i=1;i<x;i++)a[i]=a[i+1];a[x]=$0;}'  x=2 file
AIX
Solaris
Linux
 In this, an array is used which will always contain 2 lines before the current pattern. Hence, when the pattern is matched, the array contents along with the current pattern is printed.

3. Perl way:
$ perl -ne 'push @arr,$_; shift @arr if(@arr>3);
>          /Linux/ and print @arr;' file
AIX
Solaris
Linux
On reading a line, the line is pushed into an array named "arr". As and when the array size goes beyond 3, an element is removed from the front. In this way, the array will always contain 3 lines including the current pattern. On encountering the pattern 'Linux', the array is printed.

4. sed and tail combination:
$ sed -n '1,/Linux/p' file | tail -3
AIX
Solaris
Linux
Using sed, a range of lines can be read. sed reads from 1st line till the pattern 'Linux'. From this result, we print the last 3 lines which is nothing but the line containing the pattern and 2 lines before the pattern.

5. awk and sed combination:
$ x=`awk '/Linux/{print NR-2","NR}' file`
$ sed -n "$x p" file
AIX
Solaris
Linux
  Using awk, the line number range is retrieved using the pattern 'Linux'. NR gives the current line number which is the number of the line containing the pattern, NR-2 gives the gives the number of the line which is 2 lines before. Using this line range in sed, the set of lines can be filtered.

6. Another awk way, only if the file is a small one:
$ awk '{a[++i]=$0;}/Linux/{for(j=NR-2;j<=NR;j++)print a[j];}' file
AIX
Solaris
Linux
 In this, awk stores the entire file in memory using an array. On encountering the pattern 'Linux', it starts printing from 2 lines before using the for loop. Since awk stores the entire file in memory, this SHOULD not be used in case of large files since it will cause performance issues.

7. tac command (The least favored option)
$ tac file | grep -A2 Linux | tac
AIX
Solaris
Linux
tac command is reverse of cat command which prints the file in reverse order. On the reversed file, grep for 2 lines above the pattern, and again reverse the output and display. This is just an option, not the preferred one due to its performance. tac command itself is not good for performance, add to that, using it twice.
 Note: tac command is not available in all flavors of Unix. - See more at: http://www.theunixschool.com/2012/08/print-lines-before-pattern-linux.html#sthash.hDKNCoh7.dpuf
In this article, we will discuss the  different ways for how to print a few lines before a pattern match in log files. You will do well to know how to print a few lines AFTER a pattern match.

 Let us consider a sample file as below. The requirement is to print 2 lines before the pattern 'Linux':
$ cat file
Unix
AIX
Solaris
Linux
SCO
1. grep will do it for you if your grep is a GNU grep.
$ grep -B2 Linux file
AIX
Solaris
Linux
The option '-B' will give n lines before the pattern. Hence '-B2 Linux' gives 2 lines before the pattern 'Linux' including the line matching the pattern.

2. awk way:
$ awk '/Linux/{for(i=1;i<=x;)print a[i++];print}
>             {for(i=1;i<x;i++)a[i]=a[i+1];a[x]=$0;}'  x=2 file
AIX
Solaris
Linux
 In this, an array is used which will always contain 2 lines before the current pattern. Hence, when the pattern is matched, the array contents along with the current pattern is printed.

3. Perl way:
$ perl -ne 'push @arr,$_; shift @arr if(@arr>3);
>          /Linux/ and print @arr;' file
AIX
Solaris
Linux
On reading a line, the line is pushed into an array named "arr". As and when the array size goes beyond 3, an element is removed from the front. In this way, the array will always contain 3 lines including the current pattern. On encountering the pattern 'Linux', the array is printed.

4. sed and tail combination:
$ sed -n '1,/Linux/p' file | tail -3
AIX
Solaris
Linux
Using sed, a range of lines can be read. sed reads from 1st line till the pattern 'Linux'. From this result, we print the last 3 lines which is nothing but the line containing the pattern and 2 lines before the pattern.

5. awk and sed combination:
$ x=`awk '/Linux/{print NR-2","NR}' file`
$ sed -n "$x p" file
AIX
Solaris
Linux
  Using awk, the line number range is retrieved using the pattern 'Linux'. NR gives the current line number which is the number of the line containing the pattern, NR-2 gives the gives the number of the line which is 2 lines before. Using this line range in sed, the set of lines can be filtered.

6. Another awk way, only if the file is a small one:
$ awk '{a[++i]=$0;}/Linux/{for(j=NR-2;j<=NR;j++)print a[j];}' file
AIX
Solaris
Linux
 In this, awk stores the entire file in memory using an array. On encountering the pattern 'Linux', it starts printing from 2 lines before using the for loop. Since awk stores the entire file in memory, this SHOULD not be used in case of large files since it will cause performance issues.

7. tac command (The least favored option)
$ tac file | grep -A2 Linux | tac
AIX
Solaris
Linux
tac command is reverse of cat command which prints the file in reverse order. On the reversed file, grep for 2 lines above the pattern, and again reverse the output and display. This is just an option, not the preferred one due to its performance. tac command itself is not good for performance, add to that, using it twice.
 Note: tac command is not available in all flavors of Unix. - See more at: http://www.theunixschool.com/2012/08/print-lines-before-pattern-linux.html#sthash.hDKNCoh7.dpuf
In this article, we will discuss the  different ways for how to print a few lines before a pattern match in log files. You will do well to know how to print a few lines AFTER a pattern match.

 Let us consider a sample file as below. The requirement is to print 2 lines before the pattern 'Linux':
$ cat file
Unix
AIX
Solaris
Linux
SCO
1. grep will do it for you if your grep is a GNU grep.
$ grep -B2 Linux file
AIX
Solaris
Linux
The option '-B' will give n lines before the pattern. Hence '-B2 Linux' gives 2 lines before the pattern 'Linux' including the line matching the pattern.

2. awk way:
$ awk '/Linux/{for(i=1;i<=x;)print a[i++];print}
>             {for(i=1;i<x;i++)a[i]=a[i+1];a[x]=$0;}'  x=2 file
AIX
Solaris
Linux
 In this, an array is used which will always contain 2 lines before the current pattern. Hence, when the pattern is matched, the array contents along with the current pattern is printed.

3. Perl way:
$ perl -ne 'push @arr,$_; shift @arr if(@arr>3);
>          /Linux/ and print @arr;' file
AIX
Solaris
Linux
On reading a line, the line is pushed into an array named "arr". As and when the array size goes beyond 3, an element is removed from the front. In this way, the array will always contain 3 lines including the current pattern. On encountering the pattern 'Linux', the array is printed.

4. sed and tail combination:
$ sed -n '1,/Linux/p' file | tail -3
AIX
Solaris
Linux
Using sed, a range of lines can be read. sed reads from 1st line till the pattern 'Linux'. From this result, we print the last 3 lines which is nothing but the line containing the pattern and 2 lines before the pattern.

5. awk and sed combination:
$ x=`awk '/Linux/{print NR-2","NR}' file`
$ sed -n "$x p" file
AIX
Solaris
Linux
  Using awk, the line number range is retrieved using the pattern 'Linux'. NR gives the current line number which is the number of the line containing the pattern, NR-2 gives the gives the number of the line which is 2 lines before. Using this line range in sed, the set of lines can be filtered.

6. Another awk way, only if the file is a small one:
$ awk '{a[++i]=$0;}/Linux/{for(j=NR-2;j<=NR;j++)print a[j];}' file
AIX
Solaris
Linux
 In this, awk stores the entire file in memory using an array. On encountering the pattern 'Linux', it starts printing from 2 lines before using the for loop. Since awk stores the entire file in memory, this SHOULD not be used in case of large files since it will cause performance issues.

7. tac command (The least favored option)
$ tac file | grep -A2 Linux | tac
AIX
Solaris
Linux
tac command is reverse of cat command which prints the file in reverse order. On the reversed file, grep for 2 lines above the pattern, and again reverse the output and display. This is just an option, not the preferred one due to its performance. tac command itself is not good for performance, add to that, using it twice.
 Note: tac command is not available in all flavors of Unix. - See more at: http://www.theunixschool.com/2012/08/print-lines-before-pattern-linux.html#sthash.hDKNCoh7.dpuf
In this article, we will discuss the  different ways for how to print a few lines before a pattern match in log files. You will do well to know how to print a few lines AFTER a pattern match.

 Let us consider a sample file as below. The requirement is to print 2 lines before the pattern 'Linux':
$ cat file
Unix
AIX
Solaris
Linux
SCO
1. grep will do it for you if your grep is a GNU grep.
$ grep -B2 Linux file
AIX
Solaris
Linux
The option '-B' will give n lines before the pattern. Hence '-B2 Linux' gives 2 lines before the pattern 'Linux' including the line matching the pattern.

2. awk way:
$ awk '/Linux/{for(i=1;i<=x;)print a[i++];print}
>             {for(i=1;i<x;i++)a[i]=a[i+1];a[x]=$0;}'  x=2 file
AIX
Solaris
Linux
 In this, an array is used which will always contain 2 lines before the current pattern. Hence, when the pattern is matched, the array contents along with the current pattern is printed.

3. Perl way:
$ perl -ne 'push @arr,$_; shift @arr if(@arr>3);
>          /Linux/ and print @arr;' file
AIX
Solaris
Linux
On reading a line, the line is pushed into an array named "arr". As and when the array size goes beyond 3, an element is removed from the front. In this way, the array will always contain 3 lines including the current pattern. On encountering the pattern 'Linux', the array is printed.

4. sed and tail combination:
$ sed -n '1,/Linux/p' file | tail -3
AIX
Solaris
Linux
Using sed, a range of lines can be read. sed reads from 1st line till the pattern 'Linux'. From this result, we print the last 3 lines which is nothing but the line containing the pattern and 2 lines before the pattern.

5. awk and sed combination:
$ x=`awk '/Linux/{print NR-2","NR}' file`
$ sed -n "$x p" file
AIX
Solaris
Linux
  Using awk, the line number range is retrieved using the pattern 'Linux'. NR gives the current line number which is the number of the line containing the pattern, NR-2 gives the gives the number of the line which is 2 lines before. Using this line range in sed, the set of lines can be filtered.

6. Another awk way, only if the file is a small one:
$ awk '{a[++i]=$0;}/Linux/{for(j=NR-2;j<=NR;j++)print a[j];}' file
AIX
Solaris
Linux
 In this, awk stores the entire file in memory using an array. On encountering the pattern 'Linux', it starts printing from 2 lines before using the for loop. Since awk stores the entire file in memory, this SHOULD not be used in case of large files since it will cause performance issues.

7. tac command (The least favored option)
$ tac file | grep -A2 Linux | tac
AIX
Solaris
Linux
tac command is reverse of cat command which prints the file in reverse order. On the reversed file, grep for 2 lines above the pattern, and again reverse the output and display. This is just an option, not the preferred one due to its performance. tac command itself is not good for performance, add to that, using it twice.
 Note: tac command is not available in all flavors of Unix. - See more at: http://www.theunixschool.com/2012/08/print-lines-before-pattern-linux.html#sthash.hDKNCoh7.dpuf
In this article, we will discuss the  different ways for how to print a few lines before a pattern match in log files. You will do well to know how to print a few lines AFTER a pattern match.

 Let us consider a sample file as below. The requirement is to print 2 lines before the pattern 'Linux':
$ cat file
Unix
AIX
Solaris
Linux
SCO
1. grep will do it for you if your grep is a GNU grep.
$ grep -B2 Linux file
AIX
Solaris
Linux
The option '-B' will give n lines before the pattern. Hence '-B2 Linux' gives 2 lines before the pattern 'Linux' including the line matching the pattern.

2. awk way:
$ awk '/Linux/{for(i=1;i<=x;)print a[i++];print}
>             {for(i=1;i<x;i++)a[i]=a[i+1];a[x]=$0;}'  x=2 file
AIX
Solaris
Linux
 In this, an array is used which will always contain 2 lines before the current pattern. Hence, when the pattern is matched, the array contents along with the current pattern is printed.

3. Perl way:
$ perl -ne 'push @arr,$_; shift @arr if(@arr>3);
>          /Linux/ and print @arr;' file
AIX
Solaris
Linux
On reading a line, the line is pushed into an array named "arr". As and when the array size goes beyond 3, an element is removed from the front. In this way, the array will always contain 3 lines including the current pattern. On encountering the pattern 'Linux', the array is printed.

4. sed and tail combination:
$ sed -n '1,/Linux/p' file | tail -3
AIX
Solaris
Linux
Using sed, a range of lines can be read. sed reads from 1st line till the pattern 'Linux'. From this result, we print the last 3 lines which is nothing but the line containing the pattern and 2 lines before the pattern.

5. awk and sed combination:
$ x=`awk '/Linux/{print NR-2","NR}' file`
$ sed -n "$x p" file
AIX
Solaris
Linux
  Using awk, the line number range is retrieved using the pattern 'Linux'. NR gives the current line number which is the number of the line containing the pattern, NR-2 gives the gives the number of the line which is 2 lines before. Using this line range in sed, the set of lines can be filtered.

6. Another awk way, only if the file is a small one:
$ awk '{a[++i]=$0;}/Linux/{for(j=NR-2;j<=NR;j++)print a[j];}' file
AIX
Solaris
Linux
 In this, awk stores the entire file in memory using an array. On encountering the pattern 'Linux', it starts printing from 2 lines before using the for loop. Since awk stores the entire file in memory, this SHOULD not be used in case of large files since it will cause performance issues.

7. tac command (The least favored option)
$ tac file | grep -A2 Linux | tac
AIX
Solaris
Linux
tac command is reverse of cat command which prints the file in reverse order. On the reversed file, grep for 2 lines above the pattern, and again reverse the output and display. This is just an option, not the preferred one due to its performance. tac command itself is not good for performance, add to that, using it twice.
 Note: tac command is not available in all flavors of Unix. - See more at: http://www.theunixschool.com/2012/08/print-lines-before-pattern-linux.html#sthash.hDKNCoh7.dpuf
In this article, we will discuss the  different ways for how to print a few lines before a pattern match in log files. You will do well to know how to print a few lines AFTER a pattern match.

 Let us consider a sample file as below. The requirement is to print 2 lines before the pattern 'Linux':
$ cat file
Unix
AIX
Solaris
Linux
SCO
1. grep will do it for you if your grep is a GNU grep.
$ grep -B2 Linux file
AIX
Solaris
Linux
The option '-B' will give n lines before the pattern. Hence '-B2 Linux' gives 2 lines before the pattern 'Linux' including the line matching the pattern.

2. awk way:
$ awk '/Linux/{for(i=1;i<=x;)print a[i++];print}
>             {for(i=1;i<x;i++)a[i]=a[i+1];a[x]=$0;}'  x=2 file
AIX
Solaris
Linux
 In this, an array is used which will always contain 2 lines before the current pattern. Hence, when the pattern is matched, the array contents along with the current pattern is printed.

3. Perl way:
$ perl -ne 'push @arr,$_; shift @arr if(@arr>3);
>          /Linux/ and print @arr;' file
AIX
Solaris
Linux
On reading a line, the line is pushed into an array named "arr". As and when the array size goes beyond 3, an element is removed from the front. In this way, the array will always contain 3 lines including the current pattern. On encountering the pattern 'Linux', the array is printed.

4. sed and tail combination:
$ sed -n '1,/Linux/p' file | tail -3
AIX
Solaris
Linux
Using sed, a range of lines can be read. sed reads from 1st line till the pattern 'Linux'. From this result, we print the last 3 lines which is nothing but the line containing the pattern and 2 lines before the pattern.

5. awk and sed combination:
$ x=`awk '/Linux/{print NR-2","NR}' file`
$ sed -n "$x p" file
AIX
Solaris
Linux
  Using awk, the line number range is retrieved using the pattern 'Linux'. NR gives the current line number which is the number of the line containing the pattern, NR-2 gives the gives the number of the line which is 2 lines before. Using this line range in sed, the set of lines can be filtered.

6. Another awk way, only if the file is a small one:
$ awk '{a[++i]=$0;}/Linux/{for(j=NR-2;j<=NR;j++)print a[j];}' file
AIX
Solaris
Linux
 In this, awk stores the entire file in memory using an array. On encountering the pattern 'Linux', it starts printing from 2 lines before using the for loop. Since awk stores the entire file in memory, this SHOULD not be used in case of large files since it will cause performance issues.

7. tac command (The least favored option)
$ tac file | grep -A2 Linux | tac
AIX
Solaris
Linux
tac command is reverse of cat command which prints the file in reverse order. On the reversed file, grep for 2 lines above the pattern, and again reverse the output and display. This is just an option, not the preferred one due to its performance. tac command itself is not good for performance, add to that, using it twice.
 Note: tac command is not available in all flavors of Unix. - See more at: http://www.theunixschool.com/2012/08/print-lines-before-pattern-linux.html#sthash.hDKNCoh7.dpuf
In this article, we will discuss the  different ways for how to print a few lines before a pattern match in log files. You will do well to know how to print a few lines AFTER a pattern match.

 Let us consider a sample file as below. The requirement is to print 2 lines before the pattern 'Linux':
$ cat file
Unix
AIX
Solaris
Linux
SCO
1. grep will do it for you if your grep is a GNU grep.
$ grep -B2 Linux file
AIX
Solaris
Linux
The option '-B' will give n lines before the pattern. Hence '-B2 Linux' gives 2 lines before the pattern 'Linux' including the line matching the pattern.

2. awk way:
$ awk '/Linux/{for(i=1;i<=x;)print a[i++];print}
>             {for(i=1;i<x;i++)a[i]=a[i+1];a[x]=$0;}'  x=2 file
AIX
Solaris
Linux
 In this, an array is used which will always contain 2 lines before the current pattern. Hence, when the pattern is matched, the array contents along with the current pattern is printed.

3. Perl way:
$ perl -ne 'push @arr,$_; shift @arr if(@arr>3);
>          /Linux/ and print @arr;' file
AIX
Solaris
Linux
On reading a line, the line is pushed into an array named "arr". As and when the array size goes beyond 3, an element is removed from the front. In this way, the array will always contain 3 lines including the current pattern. On encountering the pattern 'Linux', the array is printed.

4. sed and tail combination:
$ sed -n '1,/Linux/p' file | tail -3
AIX
Solaris
Linux
Using sed, a range of lines can be read. sed reads from 1st line till the pattern 'Linux'. From this result, we print the last 3 lines which is nothing but the line containing the pattern and 2 lines before the pattern.

5. awk and sed combination:
$ x=`awk '/Linux/{print NR-2","NR}' file`
$ sed -n "$x p" file
AIX
Solaris
Linux
  Using awk, the line number range is retrieved using the pattern 'Linux'. NR gives the current line number which is the number of the line containing the pattern, NR-2 gives the gives the number of the line which is 2 lines before. Using this line range in sed, the set of lines can be filtered.

6. Another awk way, only if the file is a small one:
$ awk '{a[++i]=$0;}/Linux/{for(j=NR-2;j<=NR;j++)print a[j];}' file
AIX
Solaris
Linux
 In this, awk stores the entire file in memory using an array. On encountering the pattern 'Linux', it starts printing from 2 lines before using the for loop. Since awk stores the entire file in memory, this SHOULD not be used in case of large files since it will cause performance issues.

7. tac command (The least favored option)
$ tac file | grep -A2 Linux | tac
AIX
Solaris
Linux
tac command is reverse of cat command which prints the file in reverse order. On the reversed file, grep for 2 lines above the pattern, and again reverse the output and display. This is just an option, not the preferred one due to its performance. tac command itself is not good for performance, add to that, using it twice.
 Note: tac command is not available in all flavors of Unix. - See more at: http://www.theunixschool.com/2012/08/print-lines-before-pattern-linux.html#sthash.hDKNCoh7.dpuf
In this article, we will discuss the  different ways for how to print a few lines before a pattern match in log files. You will do well to know how to print a few lines AFTER a pattern match.

 Let us consider a sample file as below. The requirement is to print 2 lines before the pattern 'Linux':
$ cat file
Unix
AIX
Solaris
Linux
SCO
1. grep will do it for you if your grep is a GNU grep.
$ grep -B2 Linux file
AIX
Solaris
Linux
The option '-B' will give n lines before the pattern. Hence '-B2 Linux' gives 2 lines before the pattern 'Linux' including the line matching the pattern.

2. awk way:
$ awk '/Linux/{for(i=1;i<=x;)print a[i++];print}
>             {for(i=1;i<x;i++)a[i]=a[i+1];a[x]=$0;}'  x=2 file
AIX
Solaris
Linux
 In this, an array is used which will always contain 2 lines before the current pattern. Hence, when the pattern is matched, the array contents along with the current pattern is printed.

3. Perl way:
$ perl -ne 'push @arr,$_; shift @arr if(@arr>3);
>          /Linux/ and print @arr;' file
AIX
Solaris
Linux
On reading a line, the line is pushed into an array named "arr". As and when the array size goes beyond 3, an element is removed from the front. In this way, the array will always contain 3 lines including the current pattern. On encountering the pattern 'Linux', the array is printed.

4. sed and tail combination:
$ sed -n '1,/Linux/p' file | tail -3
AIX
Solaris
Linux
Using sed, a range of lines can be read. sed reads from 1st line till the pattern 'Linux'. From this result, we print the last 3 lines which is nothing but the line containing the pattern and 2 lines before the pattern.

5. awk and sed combination:
$ x=`awk '/Linux/{print NR-2","NR}' file`
$ sed -n "$x p" file
AIX
Solaris
Linux
  Using awk, the line number range is retrieved using the pattern 'Linux'. NR gives the current line number which is the number of the line containing the pattern, NR-2 gives the gives the number of the line which is 2 lines before. Using this line range in sed, the set of lines can be filtered.

6. Another awk way, only if the file is a small one:
$ awk '{a[++i]=$0;}/Linux/{for(j=NR-2;j<=NR;j++)print a[j];}' file
AIX
Solaris
Linux
 In this, awk stores the entire file in memory using an array. On encountering the pattern 'Linux', it starts printing from 2 lines before using the for loop. Since awk stores the entire file in memory, this SHOULD not be used in case of large files since it will cause performance issues.

7. tac command (The least favored option)
$ tac file | grep -A2 Linux | tac
AIX
Solaris
Linux
tac command is reverse of cat command which prints the file in reverse order. On the reversed file, grep for 2 lines above the pattern, and again reverse the output and display. This is just an option, not the preferred one due to its performance. tac command itself is not good for performance, add to that, using it twice.
 Note: tac command is not available in all flavors of Unix. - See more at: http://www.theunixschool.com/2012/08/print-lines-before-pattern-linux.html#sthash.hDKNCoh7.dpuf

http://www.theunixschool.com/2012/08/print-lines-before-pattern-linux.html


In this article, we will discuss the  different ways for how to print a few lines before a pattern match in log files. You will do well to know how to print a few lines AFTER a pattern match.

 Let us consider a sample file as below. The requirement is to print 2 lines before the pattern 'Linux':
$ cat file
Unix
AIX
Solaris
Linux
SCO
1. grep will do it for you if your grep is a GNU grep.
$ grep -B2 Linux file
AIX
Solaris
Linux
The option '-B' will give n lines before the pattern. Hence '-B2 Linux' gives 2 lines before the pattern 'Linux' including the line matching the pattern.

2. awk way:
$ awk '/Linux/{for(i=1;i<=x;)print a[i++];print}
>             {for(i=1;i<x;i++)a[i]=a[i+1];a[x]=$0;}'  x=2 file
AIX
Solaris
Linux
 In this, an array is used which will always contain 2 lines before the current pattern. Hence, when the pattern is matched, the array contents along with the current pattern is printed.

3. Perl way:
$ perl -ne 'push @arr,$_; shift @arr if(@arr>3);
>          /Linux/ and print @arr;' file
AIX
Solaris
Linux
On reading a line, the line is pushed into an array named "arr". As and when the array size goes beyond 3, an element is removed from the front. In this way, the array will always contain 3 lines including the current pattern. On encountering the pattern 'Linux', the array is printed.

4. sed and tail combination:
$ sed -n '1,/Linux/p' file | tail -3
AIX
Solaris
Linux
Using sed, a range of lines can be read. sed reads from 1st line till the pattern 'Linux'. From this result, we print the last 3 lines which is nothing but the line containing the pattern and 2 lines before the pattern.

5. awk and sed combination:
$ x=`awk '/Linux/{print NR-2","NR}' file`
$ sed -n "$x p" file
AIX
Solaris
Linux
  Using awk, the line number range is retrieved using the pattern 'Linux'. NR gives the current line number which is the number of the line containing the pattern, NR-2 gives the gives the number of the line which is 2 lines before. Using this line range in sed, the set of lines can be filtered.

6. Another awk way, only if the file is a small one:
$ awk '{a[++i]=$0;}/Linux/{for(j=NR-2;j<=NR;j++)print a[j];}' file
AIX
Solaris
Linux
 In this, awk stores the entire file in memory using an array. On encountering the pattern 'Linux', it starts printing from 2 lines before using the for loop. Since awk stores the entire file in memory, this SHOULD not be used in case of large files since it will cause performance issues.

7. tac command (The least favored option)
$ tac file | grep -A2 Linux | tac
AIX
Solaris
Linux
tac command is reverse of cat command which prints the file in reverse order. On the reversed file, grep for 2 lines above the pattern, and again reverse the output and display. This is just an option, not the preferred one due to its performance. tac command itself is not good for performance, add to that, using it twice.
 Note: tac command is not available in all flavors of Unix. - See more at: http://www.theunixschool.com/2012/08/print-lines-before-pattern-linux.html#sthash.hDKNCoh7.dpuf
In this article, we will discuss the different ways for how to print a few lines before a pattern match in log files. You will do well to know how to print a few lines AFTER a pattern match.

 Let us consider a sample file as below. The requirement is to print 2 lines before the pattern 'Linux':

$ cat file
Unix
AIX
Solaris
Linux
SCO

1. grep will do it for you if your grep is a GNU grep.

$ grep -B2 Linux file
AIX
Solaris
Linux

The option '-B' will give n lines before the pattern. Hence '-B2 Linux' gives 2 lines before the pattern 'Linux' including the line matching the pattern.

2. awk way:

$ awk '/Linux/{for(i=1;i<=x;)print a[i++];print}
>             {for(i=1;i<x;i++)a[i]=a[i+1];a[x]=$0;}'  x=2 file
AIX
Solaris
Linux

 In this, an array is used which will always contain 2 lines before the current pattern. Hence, when the pattern is matched, the array contents along with the current pattern is printed.

3. Perl way:

$ perl -ne 'push @arr,$_; shift @arr if(@arr>3);
>          /Linux/ and print @arr;' file
AIX
Solaris
Linux

On reading a line, the line is pushed into an array named "arr". As and when the array size goes beyond 3, an element is removed from the front. In this way, the array will always contain 3 lines including the current pattern. On encountering the pattern 'Linux', the array is printed.

4. sed and tail combination:

$ sed -n '1,/Linux/p' file | tail -3
AIX
Solaris
Linux

Using sed, a range of lines can be read. sed reads from 1st line till the pattern 'Linux'. From this result, we print the last 3 lines which is nothing but the line containing the pattern and 2 lines before the pattern.

5. awk and sed combination:

$ x=`awk '/Linux/{print NR-2","NR}' file`
$ sed -n "$x p" file
AIX
Solaris
Linux

  Using awk, the line number range is retrieved using the pattern 'Linux'. NR gives the current line number which is the number of the line containing the pattern, NR-2 gives the gives the number of the line which is 2 lines before. Using this line range in sed, the set of lines can be filtered.

6. Another awk way, only if the file is a small one:

$ awk '{a[++i]=$0;}/Linux/{for(j=NR-2;j<=NR;j++)print a[j];}' file
AIX
Solaris
Linux

 In this, awk stores the entire file in memory using an array. On encountering the pattern 'Linux', it starts printing from 2 lines before using the for loop. Since awk stores the entire file in memory, this SHOULD not be used in case of large files since it will cause performance issues.

7. tac command (The least favored option)

$ tac file | grep -A2 Linux | tac
AIX
Solaris
Linux

tac command is reverse of cat command which prints the file in reverse order. On the reversed file, grep for 2 lines above the pattern, and again reverse the output and display. This is just an option, not the preferred one due to its performance. tac command itself is not good for performance, add to that, using it twice.

 Note: tac command is not available in all flavors of Unix. - See more at: http://www.theunixschool.com/2012/08/print-lines-before-pattern-linux.html#sthash.hDKNCoh7.dpuf


Different ways to print the next few lines after pattern match



  grep, awk  or a sed command is used to print the line matching a particular pattern. However,  at times, we need to print a few more lines following the lines matching the pattern. In this article, we will see the different ways in which we can get this done. The first part explains ways to print one line following the pattern along with the pattern, few examples to print only the line following the pattern and in the end we have ways to print multiple lines following the pattern.

  Let us consider a file with the following contents as shown below:
$ cat file
Unix
Linux
Solaris
AIX
SCO
1. The simplest is using the grep command. In GNU grep, there is an option -A which prints lines following the pattern.
$ grep -A1 Linux file
Linux
Solaris
  In the above example, -A1 will print one line following the pattern along with the line matching the pattern. To print 2 lines after the pattern, it is -A2.

2. sed  has the N command which will read the next line into the pattern space.
$ sed -n '/Linux/{N;p}' file
Linux
Solaris
   First, the line containing the pattern /Linux/ is found. The command within the braces will run on the pattern found. {N;p} means read the next line and print the pattern space which now contains the current and the next line. Similarly, to print 2 lines, you can simply put: {N;N;p}. Example 7 onwards explains for printing multiple lines following the pattern.

3. awk has the getline command which reads the next line from the file.
$ awk '/Linux/{print;getline;print;}' file
Linux
Solaris
    Once the line containing the pattern Linux is found, it is printed. getline command reads the next line into $0. Hence, the second print statement prints the next line in the file.

4. In this, the same thing is achieved using only one print statement.
$ awk '/Linux/{getline x;print $0 RS x;}' file
Linux
Solaris
      getline x reads the next line into variable x. x is used in order to prevent the getline from overwriting the current line present in $0. The print statement prints the current line($0), record separator(RS) which is the newline, and the next line which is in x.

5. To print only the line following the pattern without the line matching the pattern:
$ sed  -n '/Linux/{n;p}' file
Solaris
     The n command reads the next line into the pattern space thereby overwriting the current line. On printing the pattern space using the p command, we get the next line printed.

6. Same using awk:
$ awk '/Linux/{getline;print;}' file
Solaris
Multiple lines after the pattern:
  GNU grep may not available in every Unix box. Excluding grep option, the above examples are good only to print a line or two following the pattern. Say, if you have to print some 10 lines after the pattern, the command will get clumsy. Let us now see  how to print n lines following the pattern along with the pattern:

7. To print multiple(2) lines following the pattern using awk:
$ awk '/Linux/{x=NR+2}(NR<=x){print}' file
Linux
Solaris
Aix
    To print 5 lines after the pattern, simply replace the number 2 with 5. This above example is a little tricky. Once the pattern Linux is found, x is calculated which is current line number(NR) plus 2. So, we will print lines from the current line till the line number(NR) reaches x.

8. To print 2 lines following the pattern without the line matching the pattern:
$ awk '/Linux/{x=NR+2;next}(NR<=x){print}' file
Solaris
Aix
  The next command makes the current line, which is the pattern matched, to get skipped. In this way, we can exclude the line matching the pattern from getting printed.

9. To  print 2 lines following the pattern along with the pattern matching line in another way.
$ x=`grep  -n Linux file | cut -f1 -d:`
$ awk -v ln=$x 'NR>=ln &&  NR<=ln+2' file
    Using grep and cut command, the line number of the pattern in the file is found. By passing the shell variable to awk,  we make it print only those lines whose line number is between  x and x+2.

10. One more way using sed and awk combination. First we calculate the from and to line numbers in the variables x and y. Using sed printing range of lines, we can get the same. sed can not only deal with numbers, it can work with variables as well:
$ x=`awk '/Linux/{print NR}' file`
$ y=`awk '/Linux/{print NR+2}' file`
$ sed -n "$x,$y p" file
OR
$ x=`awk '/Linux/{print NR+2}' file`
$ sed -n "/Linux/,$x p" file
- See more at: http://www.theunixschool.com/2012/05/different-ways-to-print-next-few-lines.html#sthash.9JcTMhUL.dpuf

Different ways to print the next few lines after pattern match



  grep, awk  or a sed command is used to print the line matching a particular pattern. However,  at times, we need to print a few more lines following the lines matching the pattern. In this article, we will see the different ways in which we can get this done. The first part explains ways to print one line following the pattern along with the pattern, few examples to print only the line following the pattern and in the end we have ways to print multiple lines following the pattern.

  Let us consider a file with the following contents as shown below:
$ cat file
Unix
Linux
Solaris
AIX
SCO
1. The simplest is using the grep command. In GNU grep, there is an option -A which prints lines following the pattern.
$ grep -A1 Linux file
Linux
Solaris
  In the above example, -A1 will print one line following the pattern along with the line matching the pattern. To print 2 lines after the pattern, it is -A2.

2. sed  has the N command which will read the next line into the pattern space.
$ sed -n '/Linux/{N;p}' file
Linux
Solaris
   First, the line containing the pattern /Linux/ is found. The command within the braces will run on the pattern found. {N;p} means read the next line and print the pattern space which now contains the current and the next line. Similarly, to print 2 lines, you can simply put: {N;N;p}. Example 7 onwards explains for printing multiple lines following the pattern.

3. awk has the getline command which reads the next line from the file.
$ awk '/Linux/{print;getline;print;}' file
Linux
Solaris
    Once the line containing the pattern Linux is found, it is printed. getline command reads the next line into $0. Hence, the second print statement prints the next line in the file.

4. In this, the same thing is achieved using only one print statement.
$ awk '/Linux/{getline x;print $0 RS x;}' file
Linux
Solaris
      getline x reads the next line into variable x. x is used in order to prevent the getline from overwriting the current line present in $0. The print statement prints the current line($0), record separator(RS) which is the newline, and the next line which is in x.

5. To print only the line following the pattern without the line matching the pattern:
$ sed  -n '/Linux/{n;p}' file
Solaris
     The n command reads the next line into the pattern space thereby overwriting the current line. On printing the pattern space using the p command, we get the next line printed.

6. Same using awk:
$ awk '/Linux/{getline;print;}' file
Solaris
Multiple lines after the pattern:
  GNU grep may not available in every Unix box. Excluding grep option, the above examples are good only to print a line or two following the pattern. Say, if you have to print some 10 lines after the pattern, the command will get clumsy. Let us now see  how to print n lines following the pattern along with the pattern:

7. To print multiple(2) lines following the pattern using awk:
$ awk '/Linux/{x=NR+2}(NR<=x){print}' file
Linux
Solaris
Aix
    To print 5 lines after the pattern, simply replace the number 2 with 5. This above example is a little tricky. Once the pattern Linux is found, x is calculated which is current line number(NR) plus 2. So, we will print lines from the current line till the line number(NR) reaches x.

8. To print 2 lines following the pattern without the line matching the pattern:
$ awk '/Linux/{x=NR+2;next}(NR<=x){print}' file
Solaris
Aix
  The next command makes the current line, which is the pattern matched, to get skipped. In this way, we can exclude the line matching the pattern from getting printed.

9. To  print 2 lines following the pattern along with the pattern matching line in another way.
$ x=`grep  -n Linux file | cut -f1 -d:`
$ awk -v ln=$x 'NR>=ln &&  NR<=ln+2' file
    Using grep and cut command, the line number of the pattern in the file is found. By passing the shell variable to awk,  we make it print only those lines whose line number is between  x and x+2.

10. One more way using sed and awk combination. First we calculate the from and to line numbers in the variables x and y. Using sed printing range of lines, we can get the same. sed can not only deal with numbers, it can work with variables as well:
$ x=`awk '/Linux/{print NR}' file`
$ y=`awk '/Linux/{print NR+2}' file`
$ sed -n "$x,$y p" file
OR
$ x=`awk '/Linux/{print NR+2}' file`
$ sed -n "/Linux/,$x p" file
- See more at: http://www.theunixschool.com/2012/05/different-ways-to-print-next-few-lines.html#sthash.9JcTMhUL.dpuf
Different ways to print the next few lines after pattern match

http://www.theunixschool.com/2012/05/different-ways-to-print-next-few-lines.html


  grep, awk  or a sed command is used to print the line matching a particular pattern. However,  at times, we need to print a few more lines following the lines matching the pattern. In this article, we will see the different ways in which we can get this done. The first part explains ways to print one line following the pattern along with the pattern, few examples to print only the line following the pattern and in the end we have ways to print multiple lines following the pattern.

  Let us consider a file with the following contents as shown below:

$ cat file
Unix
Linux
Solaris
AIX
SCO

1. The simplest is using the grep command. In GNU grep, there is an option -A which prints lines following the pattern.

$ grep -A1 Linux file
Linux
Solaris

  In the above example, -A1 will print one line following the pattern along with the line matching the pattern. To print 2 lines after the pattern, it is -A2.

2. sed  has the N command which will read the next line into the pattern space.

$ sed -n '/Linux/{N;p}' file
Linux
Solaris

   First, the line containing the pattern /Linux/ is found. The command within the braces will run on the pattern found. {N;p} means read the next line and print the pattern space which now contains the current and the next line. Similarly, to print 2 lines, you can simply put: {N;N;p}. Example 7 onwards explains for printing multiple lines following the pattern.

3. awk has the getline command which reads the next line from the file.

$ awk '/Linux/{print;getline;print;}' file
Linux
Solaris

    Once the line containing the pattern Linux is found, it is printed. getline command reads the next line into $0. Hence, the second print statement prints the next line in the file.

4. In this, the same thing is achieved using only one print statement.

$ awk '/Linux/{getline x;print $0 RS x;}' file
Linux
Solaris

     getline x reads the next line into variable x. x is used in order to prevent the getline from overwriting the current line present in $0. The print statement prints the current line($0), record separator(RS) which is the newline, and the next line which is in x.

5. To print only the line following the pattern without the line matching the pattern:

$ sed  -n '/Linux/{n;p}' file
Solaris

     The n command reads the next line into the pattern space thereby overwriting the current line. On printing the pattern space using the p command, we get the next line printed.

6. Same using awk:

$ awk '/Linux/{getline;print;}' file
Solaris

Multiple lines after the pattern:
  GNU grep may not available in every Unix box. Excluding grep option, the above examples are good only to print a line or two following the pattern. Say, if you have to print some 10 lines after the pattern, the command will get clumsy. Let us now see  how to print n lines following the pattern along with the pattern:

7. To print multiple(2) lines following the pattern using awk:

$ awk '/Linux/{x=NR+2}(NR<=x){print}' file
Linux
Solaris
Aix

    To print 5 lines after the pattern, simply replace the number 2 with 5. This above example is a little tricky. Once the pattern Linux is found, x is calculated which is current line number(NR) plus 2. So, we will print lines from the current line till the line number(NR) reaches x.

8. To print 2 lines following the pattern without the line matching the pattern:

$ awk '/Linux/{x=NR+2;next}(NR<=x){print}' file
Solaris
Aix

  The next command makes the current line, which is the pattern matched, to get skipped. In this way, we can exclude the line matching the pattern from getting printed.

9. To print 2 lines following the pattern along with the pattern matching line in another way.

$ x=`grep  -n Linux file | cut -f1 -d:`
$ awk -v ln=$x 'NR>=ln &&  NR<=ln+2' file

    Using grep and cut command, the line number of the pattern in the file is found. By passing the shell variable to awk,  we make it print only those lines whose line number is between  x and x+2.

10. One more way using sed and awk combination. First we calculate the from and to line numbers in the variables x and y. Using sed printing range of lines, we can get the same. sed can not only deal with numbers, it can work with variables as well:

$ x=`awk '/Linux/{print NR}' file`
$ y=`awk '/Linux/{print NR+2}' file`
$ sed -n "$x,$y p" file

OR

$ x=`awk '/Linux/{print NR+2}' file`
$ sed -n "/Linux/,$x p" file

- See more at: http://www.theunixschool.com/2012/05/different-ways-to-print-next-few-lines.html#sthash.9JcTMhUL.dpuf



In this article, we will discuss the  different ways for how to print a few lines before a pattern match in log files. You will do well to know how to print a few lines AFTER a pattern match.

 Let us consider a sample file as below. The requirement is to print 2 lines before the pattern 'Linux':
$ cat file
Unix
AIX
Solaris
Linux
SCO
1. grep will do it for you if your grep is a GNU grep.
$ grep -B2 Linux file
AIX
Solaris
Linux
The option '-B' will give n lines before the pattern. Hence '-B2 Linux' gives 2 lines before the pattern 'Linux' including the line matching the pattern.

2. awk way:
$ awk '/Linux/{for(i=1;i<=x;)print a[i++];print}
>             {for(i=1;i<x;i++)a[i]=a[i+1];a[x]=$0;}'  x=2 file
AIX
Solaris
Linux
 In this, an array is used which will always contain 2 lines before the current pattern. Hence, when the pattern is matched, the array contents along with the current pattern is printed.

3. Perl way:
$ perl -ne 'push @arr,$_; shift @arr if(@arr>3);
>          /Linux/ and print @arr;' file
AIX
Solaris
Linux
On reading a line, the line is pushed into an array named "arr". As and when the array size goes beyond 3, an element is removed from the front. In this way, the array will always contain 3 lines including the current pattern. On encountering the pattern 'Linux', the array is printed.

4. sed and tail combination:
$ sed -n '1,/Linux/p' file | tail -3
AIX
Solaris
Linux
Using sed, a range of lines can be read. sed reads from 1st line till the pattern 'Linux'. From this result, we print the last 3 lines which is nothing but the line containing the pattern and 2 lines before the pattern.

5. awk and sed combination:
$ x=`awk '/Linux/{print NR-2","NR}' file`
$ sed -n "$x p" file
AIX
Solaris
Linux
  Using awk, the line number range is retrieved using the pattern 'Linux'. NR gives the current line number which is the number of the line containing the pattern, NR-2 gives the gives the number of the line which is 2 lines before. Using this line range in sed, the set of lines can be filtered.

6. Another awk way, only if the file is a small one:
$ awk '{a[++i]=$0;}/Linux/{for(j=NR-2;j<=NR;j++)print a[j];}' file
AIX
Solaris
Linux
 In this, awk stores the entire file in memory using an array. On encountering the pattern 'Linux', it starts printing from 2 lines before using the for loop. Since awk stores the entire file in memory, this SHOULD not be used in case of large files since it will cause performance issues.

7. tac command (The least favored option)
$ tac file | grep -A2 Linux | tac
AIX
Solaris
Linux
tac command is reverse of cat command which prints the file in reverse order. On the reversed file, grep for 2 lines above the pattern, and again reverse the output and display. This is just an option, not the preferred one due to its performance. tac command itself is not good for performance, add to that, using it twice.
 Note: tac command is not available in all flavors of Unix. - See more at: http://www.theunixschool.com/2012/08/print-lines-before-pattern-linux.html#sthash.hDKNCoh7.dpuf
In this article, we will discuss the  different ways for how to print a few lines before a pattern match in log files. You will do well to know how to print a few lines AFTER a pattern match.

 Let us consider a sample file as below. The requirement is to print 2 lines before the pattern 'Linux':
$ cat file
Unix
AIX
Solaris
Linux
SCO
1. grep will do it for you if your grep is a GNU grep.
$ grep -B2 Linux file
AIX
Solaris
Linux
The option '-B' will give n lines before the pattern. Hence '-B2 Linux' gives 2 lines before the pattern 'Linux' including the line matching the pattern.

2. awk way:
$ awk '/Linux/{for(i=1;i<=x;)print a[i++];print}
>             {for(i=1;i<x;i++)a[i]=a[i+1];a[x]=$0;}'  x=2 file
AIX
Solaris
Linux
 In this, an array is used which will always contain 2 lines before the current pattern. Hence, when the pattern is matched, the array contents along with the current pattern is printed.

3. Perl way:
$ perl -ne 'push @arr,$_; shift @arr if(@arr>3);
>          /Linux/ and print @arr;' file
AIX
Solaris
Linux
On reading a line, the line is pushed into an array named "arr". As and when the array size goes beyond 3, an element is removed from the front. In this way, the array will always contain 3 lines including the current pattern. On encountering the pattern 'Linux', the array is printed.

4. sed and tail combination:
$ sed -n '1,/Linux/p' file | tail -3
AIX
Solaris
Linux
Using sed, a range of lines can be read. sed reads from 1st line till the pattern 'Linux'. From this result, we print the last 3 lines which is nothing but the line containing the pattern and 2 lines before the pattern.

5. awk and sed combination:
$ x=`awk '/Linux/{print NR-2","NR}' file`
$ sed -n "$x p" file
AIX
Solaris
Linux
  Using awk, the line number range is retrieved using the pattern 'Linux'. NR gives the current line number which is the number of the line containing the pattern, NR-2 gives the gives the number of the line which is 2 lines before. Using this line range in sed, the set of lines can be filtered.

6. Another awk way, only if the file is a small one:
$ awk '{a[++i]=$0;}/Linux/{for(j=NR-2;j<=NR;j++)print a[j];}' file
AIX
Solaris
Linux
 In this, awk stores the entire file in memory using an array. On encountering the pattern 'Linux', it starts printing from 2 lines before using the for loop. Since awk stores the entire file in memory, this SHOULD not be used in case of large files since it will cause performance issues.

7. tac command (The least favored option)
$ tac file | grep -A2 Linux | tac
AIX
Solaris
Linux
tac command is reverse of cat command which prints the file in reverse order. On the reversed file, grep for 2 lines above the pattern, and again reverse the output and display. This is just an option, not the preferred one due to its performance. tac command itself is not good for performance, add to that, using it twice.
 Note: tac command is not available in all flavors of Unix. - See more at: http://www.theunixschool.com/2012/08/print-lines-before-pattern-linux.html#sthash.hDKNCoh7.dpuf

ubantu端使用命令直接在Windows端打开文件或目录 本文介绍了一种基于网络通信的跨平台文件访问方法,通过Ubuntu向Windows发送指令来打开共享文件。作者实现了面向过程的C程序,主要功能包括:1)获取IP地址和文件路径;2)转换路径格式为Windows可识别格式;3)通过curl命令向Windows端发送打开文件/目录的请求。在Ubuntu端编译程序并配置环境变量后,可直接通过fw命令触发操作。Windows端需运行Python脚本监听8080端口来接收并执行指令。该方法为Linux/Android底层开发人员提供了便捷的跨平台文件访问方案。 阅读详情

相关推荐

CentOS 7 从 firewalld 迁移到 iptables 的工程实践指南

iptables 是 Linux 内核 Netfilter 框架的命令行接口,通过直接操作四表五链(filter、nat、mangle、raw)实现细粒度网络包过滤与地址转换。其核心原理基于规则匹配顺序、连接状态跟踪(conntrack)及模块化扩展(如 xt_time、ipset),技术价值在于零抽象、高确定性与强可审计性,广泛应用于生产环境防火墙加固、Docker/KVM 网络协同、等保合规策略落地及 AI 工具链(如 Free-Claude-Code)的端口映射部署。本文聚焦 CentOS 7 平台,

diaoqu4574的博客 344

项目介绍之论文格式的自动检测与修改系统

项目背景:此项目隶属于大连理工大学国家级创业训练项目,由三个人负责主要的模块的开发,并交由实验室网站组上线,主要解决高校毕业生论文格式不规范,而人工检查费时费力这一现实问题。 项目内容:此项目的在于检测论文中所有格式错误,并加以修改。可以得到整篇论文的错误格式报告和修改格式后的论文。 通过运用OpenXMLSDK,比较和修改用户上传的论文的XML标签与标准模板XML...

测试 8924

docker一键部署笔记

默认 登录用户名: postgres如果遇到 FATAL: password authentication failed for user "XXX"有可能防火墙的问题,禁止外部访问解决方法: 在 data 的 pg_hba.conf 中的 ipv4 添加以下一行。

Angindem博客 462

CSS伪类before,after制作左右横线中间文字效果

html lang="en"> head> meta charset="UTF-8"> title>Titletitle> style> .container{ width: 1000px; margin: 10px auto; border: 1px solid red;

baidu_33163851的博客 4万+

YOLOv8乳腺X光检测:900张标注数据集与训练避坑指南

目标检测模型的性能高度依赖训练数据的质量和格式。对于医学影像中的乳腺X光(钼靶)病灶检测,YOLOv8作为主流检测框架,其输入数据需遵循统一的YOLO标注格式和归一化坐标规范。然而,公开数据集如RSNA、MIAS等原始格式各异,直接使用会面临坐标体系转换、标签冲突、患者信息泄漏等一系列问题。通过整合多个公开数据集并进行清洗,可以构建一个可直接用于YOLOv8训练的标注数据集,这不仅能显著降低数据预处理成本,还能为后续算法迭代提供稳定基线。在实际工程应用中,从数据校验、类别平衡到按病例划分训练集,每一步都隐藏

weixin_34228387的博客 340

玩转ubuntu18 --机器视觉方面(yolo算法识别及摄像头和cmake问题解决)

玩转ubuntu18 --机器视觉方面(yolo v3算法识别) 1.YOLO的简介 工作原理 先前的检测系统重新调整分类器或本地化器以执行检测。他们将模型应用于多个位置和比例尺的图像。图像的高分区域被视为检测。 我们使用完全不同的方法。我们将单个神经网络应用于整个图像。该网络将图像划分为区域,并预测每个区域的边界框和概率。这些边界框按预测概率加权。 我们的模型比基于分类器的系统具有几个优势。它在测试时间查看整个图像,因此其预测由图像中的全球上下文提供信息。它还通过单一网络评估进行预测,这与R-CNN等系统

qq_53951823的博客 1556

WordProcessingML的解剖学翻译04--Wordprocessing段落02--属性06--间距

Wordprocessing 段落 – 属性 间距 段落之间和段落的行之间的间距由 <w:spacing>元素定义。 <w:pPr> <w:spacing w:before="120" w:after="120" w:beforeAutospacing="0" w:afterAutospacing="0"/> </w:pPr> <w:pPr...

JovenGeek的博客 1491

重磅!Repo Wiki!

RepoWiki是Qoder平台的智能文档生成功能,通过静态代码分析自动提取项目架构、模块依赖和核心逻辑,并持续追踪代码变更保持文档同步。其工作流程分为四个阶段:1)代码扫描与AST解析;2)结构分析与依赖映射;3)文档智能生成;4)增量更新机制。支持多种编程语言,能识别设计模式并推断技术决策,适用于新项目搭建和遗留系统维护。优势在于降低理解成本和提高开发效率,但存在文件数量限制和依赖Git的局限性。典型应用场景包括自动生成架构图、API手册和团队知识沉淀。

ayusong870的博客 4028

Wisp:融合Lua与Shell管道的Linux自动化脚本新方案

在Linux系统管理与自动化运维领域,Shell脚本是处理命令行任务的基础工具,但其语法晦涩、数据结构单一等局限性常使复杂逻辑的实现变得困难。现代脚本语言如Python虽功能强大,但与Shell环境集成时存在启动开销大、管道操作不够直观等问题。为解决这些痛点,一种创新的技术方案应运而生:将轻量级脚本语言与Shell管道思想深度融合。Wisp正是这一理念的实践,它通过引入Lua作为脚本引擎,重新定义了命令管道的交互方式,实现了结构化数据的无缝传递。这种融合不仅提升了脚本的可读性和可维护性,还显著增强了数据处理

weixin_30598225的博客 374

动力学约束下的运动规划算法——Kinodynamic RRT*算法

动力学约束下的运动规划算法——Kinodynamic RRT*算法

慕羽★的博客 6749

RK3568笔记二:部署手写数字识别模型

部署手写数字识别模型,使用手写数字识别(mnist)数据集训练了一个 LENET 的五层经典网络模型。Lenet是我们的深度学习入门的必学模型,是深度学习领域中的经典卷积神经网络(CNN)架构之一。过程分为:训练,导出ONNX,转化RKNN,测试。

1170

shell脚本学习

本文系统介绍了Linux shell的基础知识,涵盖passwd文件结构、shell内建命令与脚本执行机制、变量定义与分类(全局、局部、环境变量)、文件名通配符、命令与算术代换、引号使用、条件测试、分支与循环结构(if、case、for、while),以及位置参数和特殊变量(如$0、$1、$@、$?、$$)的应用。内容详实,适用于Shell编程入门与实践参考。

Demilly123的博客 75

UG NX二次开发基础篇-外部模式与DLL内部模式(二 DLL内部模式)

通常情况下,我们希望我们的外挂,在UG启动的时候,就自动加载我们的外挂,并以菜单和工具条的方式,显示在UG上面。当然,这也是市面上所有外挂的操作,因为您不可能要求你的用户,以手工加载的方式,去调用你的外挂吧。在上一篇中,有粉丝留言说,启动 bat 文件,启动EXE外挂,会提示无法找到DLL的错误,这是因为UG的环境变量设置有问题,这里,我们把BAT文件作一个修改,直接改为实际目录。EXE外部模式,还有很多部分需要添加的,如参数的传递、输出消息的显示、UG操作的消息显示,等等。Dll执行结束后,会调用。

u014657217的博客 1654

Liunx:正则表达式,三剑客以及ansible 环境准备和配置

正则表达式作为一个pattern,将pattern与要搜索的字符串进行匹配,以便查找一个或多个字符串。正则表达式,自成体系,由普通字符(例如字符 a 到 z)和元字符组成的文字模式。普通字符:没有显式指定为元字符的所有可打印和不可打印字符字符,包括所有大写和小写字母、所有数字、所有标点符号和其他一些符号。元字符:除了普通字符之外的字符。正则表达式,工具(vim、grep、less等)和程序语言(Perl、Python、C等)都使用正则表达式。普通正则表达式扩展正则表示,支持更多的元字符。

Kismet_nvi的博客 414

【基于深度学习的脑电图识别】数据集篇:THE TUH EEG CORPUS: A Big Data Resource for Automated EEG Interpretation

【基于机器学习的脑电图识别】数据集篇:脑电信号自动判读的大数据摘要: 摘要: 这个数据集包括超过 25000 个脑电图研究,包括一个神经学家对测试的解释,一个简短的病人病史和关于病人的人口统计信息,如性别和年龄。这是第一次有足够的数据来支持最先进的机器学习算法的应用。在这篇论文中,我们使用了3762个语料库的会话子集,展示了从原始脑电图信号数据预测脑电图的一些基本属性的初步实验结果。在闭环测试中,...

梁瑛平的博客 5615

【电机应用控制】——步进电机控制原理(四相五线/两相四线/细分驱动)&驱动器&梯形/S形加减速算法&直线/圆弧插补

步进电机是一种把电脉冲信号转换为角位移(左)或线位移(右)的电动机。两相通常1.8°,三相通常1.2°、无相通常0.72°,角位移=脉冲个数X步距角。在非超载且不超频的情况下,电机的旋转位置只取决于脉冲个数,转速只取决脉冲信号的频率。所以只需要统计脉冲个数和频率,不再需要编码器测速和位置,具有优秀的开环能力,当然也可接编码器反馈速度和位置数据,实现更加精准的闭环控制。永磁式动态性能好,输出力矩大,但步距角大通常7.5°;反应式(磁阻式)结构简单成本低,步距角小一般1.2°,但振动噪音大动态性能差;

weixin_51658186的博客 5万+

statusline-command.sh Claude code 自定义状态栏

编辑顶部的配置:CACHE_DIR="${HOME}/.claude/statusline-cache" # 缓存目录CACHE_TTL_DAYS=7 # 缓存保留天数颜色阈值(约第 190 行):then # >80% 红色then # 51-80% 绿色else # ≤50% 灰色fi/bin/bashJQ=""dothenthen。

vistaup的博客 262

Windows 下运行 openclaw 出现“‘openclaw‘ 不是内部或外部命令,也不是可运行的程序或批处理文件“的解决方案

方案适用场景推荐指数检查并手动添加 PATH明确知道全局安装目录,只是没加进PATH⭐⭐⭐⭐⭐pnpm setup 自动配置使用 pnpm 安装,想要省心的自动化方式⭐⭐⭐⭐⭐npx 免安装临时运行快速验证核心程序是否正常,排除法排查⭐⭐⭐⭐清理残留后重装npm/pnpm 混用导致版本混乱⭐⭐⭐⭐改用 WSL2不熟悉 Windows 路径体系,长期使用⭐⭐⭐'openclaw' 不是内部或外部命令这类报错,本质上不是"程序坏了",而是。

一键难忘的博客 1万+

Linux运维实战

去阿里源、清华源。

weixin_57136547的博客 286

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

Navi 速查表(Cheatsheet)语法完全指南:从基础元素到变量依赖、代码片段与别名

Navi 是一款面向命令行的交互式速查表工具,它通过解析 `.cheat` / `.cheat.md` 文件,把常见的 shell 命令封装成带变量、可选参数和实时预览的交互式菜单。本文以官方语法文档 [docs/cheatsheet/syntax/README.md](https://link.gitcode.com/i/837ecec2b31fb480b52053df85cb32da) 为主体

gitblog_01149的博客 305

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

QE(quantum-espresso)各类计算汇总

横坐标做变换x'=x*0.5292*2*pi/a, 其中a是晶格常数(认为是垂直与高对称路径面的方向,比如走g2-g3面,则a是x方向的晶格)。x是原来的坐标,x'是变换单位后的坐标。----在构造 ε₂ 时,价带 → 导带跃迁的 δ 函数被替换为宽度为 intersmear 的高斯/洛仑兹函数。----带内主要出现在金属系统(自由电子或接近费米面的跃迁)。其中X0就是求出的价带顶二阶导数值,a为晶格常数值(求G-X方向就是晶格常数a,求G-Y方向就是晶格常数b).则m*=1/(2*C)m0。

weixin_51602307的博客 389

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

工作中使用到的单词(软件开发)

1.エイリアス   alias 别名 powershell使用 get-help 命令时,会得到与此命令 相关(别名)的命令 2.プロキシ proxy 代 理 3.プロモート   promote 促进,提升   开发的系统新功能上线发布,有时会使用到这个词,比如 STプロモート 还有使用リリース这个词的。比如STリリース。个人认为两者含义相同。 4.見逃し み................................................................

sun0322 6万+

运维实战笔记(八):正则表达式与 grep、sed 文本处理实战

正则表达式作为一个pattern,将pattern与要搜索的字符串进行匹配,以便查找一个或多个字符串。正则表达式,自成体系,由普通字符(例如字符 a 到 z)和元字符组成的文字模式。普通字符:没有显式指定为元字符的所有可打印和不可打印字符字符,包括所有大写和小写字母、所有数字、所有标点符号和其他一些符号。元字符:除了普通字符之外的字符。正则表达式,工具(vim、grep、less等)和程序语言(Perl、Python、C等)都使用正则表达式。普通正则表达式扩展正则表示,支持更多的元字符。

zx7854的博客 379

MySQL 到 Greenplum 定时增量数据同步脚本集

定时自动调度执行、通用文件、增量数据同步脚本、MySQL 增量数据导出脚本、将增量数据导入到 Greenplum 的过渡区表中、将增量数据合并到数仓表、检查增量数据同步执行日志、联合实时数据维护删除标志

wzy0623的专栏 1484

Nagios Python插件开发:CentOS 6兼容性与退出码契约实践

Nagios插件本质是遵循严格退出码契约(0/1/2/3)的命令行接口,其核心价值在于为监控系统提供可预测、可诊断的状态信号。在老旧环境如CentOS 6中,Python 2.6.6缺失argparse、json等基础模块,导致插件静默失败并返回UNKNOWN,暴露出运行时环境与契约执行之间的深层矛盾。本文从Nagios监控原理出发,解析退出码语义、stdout/stderr职责分离、超时控制与错误上下文设计四大技术支柱,结合独立Python运行时构建、sudo权限最小化授权、SMART底层健康检查等工程实

weixin_30321449的博客 393

tcl 脚本合集

【代码】tcl 脚本合集。

zh_404的博客 66
上一篇: ssh without no password
下一篇: Threads vs. Async
michaelrun
博客等级 码龄19年 93粉丝 50原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值