如何在搜索模式之间获取内容
How to get content between the search patterns
我有一些这种格式的文本。
echo "Hi"
line A
line B
echo "hello"
line C
echo "him"
line D
echo "hind legs"
当我为 "hi" grep 时,我会得到
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"
请帮忙。
sed -ne '/echo "Hi"/,/echo "him"/p' file > data1
sed -ne '/echo "him"/,/echo "hind legs"/p' file > data2
这个 awk 会将输入分成几个文件 data1.txt
、data2.txt
等等:
awk 'tolower([=10=]) ~ "hi" { if(fname) { print > fname; close(fname) } ++n; fname = "data" n ".txt" } { print > fname }' filename
它的工作原理如下:
tolower([=11=]) ~ "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
}
我有一些这种格式的文本。
echo "Hi"
line A
line B
echo "hello"
line C
echo "him"
line D
echo "hind legs"
当我为 "hi" grep 时,我会得到
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"
请帮忙。
sed -ne '/echo "Hi"/,/echo "him"/p' file > data1
sed -ne '/echo "him"/,/echo "hind legs"/p' file > data2
这个 awk 会将输入分成几个文件 data1.txt
、data2.txt
等等:
awk 'tolower([=10=]) ~ "hi" { if(fname) { print > fname; close(fname) } ++n; fname = "data" n ".txt" } { print > fname }' filename
它的工作原理如下:
tolower([=11=]) ~ "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
}