使用sed在两种模式之间进行打印

时间:2012-09-15 22:57:20

标签: linux bash sed awk

所以我在deleting the text between two patternsprinting the text between two delimiters上找到了很多东西,但我没有找到任何关于使用bash函数在两个模式之间打印文本的内容。

如果我有:

"Alas poor Yorik, I knew him well"

我希望打印“穷人”和“好”(独家)模式之间的所有内容我会得到:

" Yorik, I knew him "

我怎么能用sed或awk这样的东西来实现呢?

1 个答案:

答案 0 :(得分:5)

dtpwmbp:~ pwadas$ echo "Alas poor Yorik, I knew him well" | sed -e 's/^.*poor //g;s/ well.*$//g'
Yorik, I knew him
dtpwmbp:~ pwadas$ echo "Alas poor Yorik, I knew him well" | awk '{sub(/.*poor /,"");sub(/ well.*/,"");print;}'
Yorik, I knew him

使用文件输入:

dtpwmbp:~ pwadas$ echo "Alas poor Yorik, I knew him well" > infile
dtpwmbp:~ pwadas$ cat infile 
Alas poor Yorik, I knew him well
dtpwmbp:~ pwadas$ cat infile | sed -e 's/^.*poor //g;s/ well.*$//g'
Yorik, I knew him
dtpwmbp:~ pwadas$ sed -e 's/^.*poor //g;s/ well.*$//g' < infile
Yorik, I knew him
dtpwmbp:~ pwadas$ cat infile | awk '{sub(/.*poor /,"");sub(/ well.*/,"");print;}'
Yorik, I knew him
dtpwmbp:~ pwadas$ awk '{sub(/.*poor /,"");sub(/ well.*/,"");print;}' < infile 
Yorik, I knew him