代码grep3line.sh
以下脚本的功能是查找文本的匹配字符串,然后打印匹配字符串所在行的前一行,匹配字符串所在行,匹配字符串所在行后一行。然后以___(三个下划线)结尾
#!/bin/sh
# grep3 - prints out three lines around pattern
# if there is only one argument, exit
case $# in
1);;
*) echo "Usage: $0 pattern";exit;;
esac;
# I hope the argument doesn't contain a /
# if it does, sed will complain
# use sed -n to disable printing
# unless we ask for it
sed -n '
'/$1/' !{
#no match - put the current line in the hold buffer
x
# delete the old one, which is
# now in the pattern buffer
d
}
'/$1/' {
# a match - get last line
x
# print it
p
# get the original line back
x
# print it
p
# get the next line
n
# print it
p
# now add three dashes as a marker
a\
---
# now put this line into the hold buffer
x
}'
执行脚本
echo -e '1\n2\n3\n4' | ./grep3line.sh 2
# 输出
1
2
3
___
网友评论