What is the replacement/equivalent of grep
As Unix does not offer -A
or -B
options with grep, I am looking for the way to achieve the same result in Unix. The purpose is to print all the lines not starting with a specific pattern and the preceding line.
grep -B1 -v '^This' Filename
This will print all the lines not starting with the string 'This'
and the preceding line. Unfortunately my script needs to be run on Unix. Any workaround will be great.
You can use awk
:
awk '/pattern/{if(NR>1){print previous};print}{previous=$0}'
Explanation:
# If the pattern is found
/pattern/ {
# Print the previous line. The previous line is only set if the current
# line is not the first line.
if (NR>1) {
print previous
}
# Print the current line
print
}
# This block will get executed on every line
{
# Backup the current line for the case that the next line matches
previous=$0
}
链接地址: http://www.djcxy.com/p/19638.html
上一篇: 正则表达式匹配错误和相关的几行
下一篇: 什么是grep的替代/等价物