如何在搜索模式之间获取内容

时间:2015-03-20 05:37:26

标签: shell awk sed grep sh

我有一些这种格式的文字。

echo "Hi"
line A 
line B
echo "hello"
line C
echo "him"
line D
echo "hind legs" 

当我贪吃“嗨”时,我会得到

echo "Hi"
echo "him"
echo "hind legs"     

我的要求是获取搜索行之间的所有行。 要求输出:

数据1:

echo "Hi"
line A 
line B
echo "hello"
line C
echo "him"

数据2:

echo "him"
line D
echo "hind legs" 

请帮助。

2 个答案:

答案 0 :(得分:1)

sed -ne '/echo "Hi"/,/echo "him"/p' file > data1
sed -ne '/echo "him"/,/echo "hind legs"/p' file > data2

答案 1 :(得分:1)

此awk会将输入拆分为多个文件data1.txtdata2.txt等等:

awk 'tolower($0) ~ "hi" { if(fname) { print > fname; close(fname) } ++n; fname = "data" n ".txt" } { print > fname }' filename

它的工作原理如下:

tolower($0) ~ "hi" {         # If a line matches the search pattern
                             # case-insensitively,
  if(fname) {                # if there is a current file (i.e., if this is
                             # not the first delimiter line),
    print > fname            # print it to the current file
    close(fname)             # then close that file
  }
  ++n                        # increase counter
  fname = "data" n ".txt"    # build new file name
}
{
  print > fname              # print lines to that current file
}