Shell 如何在搜索模式之间获取内容
我有一些这种格式的文本Shell 如何在搜索模式之间获取内容,shell,awk,sed,grep,sh,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 "hi
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"
请提供帮助。此awk将把输入拆分为几个文件
data1.txt
,data2.txt
,等等:
sed -ne '/echo "Hi"/,/echo "him"/p' file > data1
sed -ne '/echo "him"/,/echo "hind legs"/p' file > data2
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
}
您希望输出在两个单独的文件中吗?可以将其放在两个单独的文件中,也可以放在不同的变量中。我的搜索模式仅为“hi”。我没有多个搜索模式。