Unix 中 grep -B / -A 选项的 replacement/equivalent 是什么?
What is the replacement/equivalent of grep -B / -A option in Unix?
由于 Unix 不提供 -A
或 -B
grep 选项,我正在寻找在 Unix 中实现相同结果的方法。
目的是打印所有不以特定模式开头的行和前面的行。
grep -B1 -v '^This' Filename
这将打印所有不以字符串 'This'
和前一行开头的行。不幸的是,我的脚本在 Unix 上需要 运行。
任何解决方法都会很好。
您可以使用 awk
:
awk '/pattern/{if(NR>1){print previous};print}{previous=[=10=]}'
解释:
# 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=[=11=]
}
由于 Unix 不提供 -A
或 -B
grep 选项,我正在寻找在 Unix 中实现相同结果的方法。
目的是打印所有不以特定模式开头的行和前面的行。
grep -B1 -v '^This' Filename
这将打印所有不以字符串 'This'
和前一行开头的行。不幸的是,我的脚本在 Unix 上需要 运行。
任何解决方法都会很好。
您可以使用 awk
:
awk '/pattern/{if(NR>1){print previous};print}{previous=[=10=]}'
解释:
# 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=[=11=]
}