I have a file "Input_file" with content like this
我有一个文件“Input_file”,内容如下
%name=ABC
%value=123
sample text in file
sample text in file
%name=XYZ
%value=789
sample text in file
I need to extract the lines of this file matching this pattern.
我需要提取匹配此模式的此文件的行。
str="%name=*\n%value=*"
I was working this way
我这样做
gawk -v st=$str '/"$st"/ {print}' $Input_file
I'm getting the error
我收到了错误
gawk: ^ backslash not last character on line
Even with grep as in
即使用grep也是如此
grep -e "$str" $Input_file
it says there is no such matching pattern. Where am I going wrong.
它说没有这样的匹配模式。我哪里错了。
3 个解决方案
#1
2
Try this:
尝试这个:
grep -A1 "^%name=" $Input_file | grep -B1 "^%value=" | grep -v "^--"
#2
1
you cannot directly use your "pattern (str)" in awk. because awk default doesn't work in multi-line mode. However you could do this with awk:
你不能直接在awk中使用你的“pattern(str)”。因为awk默认在多行模式下不起作用。但是你可以用awk做到这一点:
awk '/^%name=/{n=$0;next}/^%value=/&&n{print n"\n"$0}{n=""}' file
with your example, the above one-liner outputs:
以你的例子,上面的单线输出:
%name=ABC
%value=123
%name=XYZ
%value=789
#3
0
You can use a different syntax in your $str variable, the '*' is useless in because you are searching a pattern not a literal value, for gawk I can't help sorry
你可以在你的$ str变量中使用不同的语法,'*'是无用的因为你正在搜索模式而不是文字值,因为gawk我不能抱歉
try this:
尝试这个:
str="\%name=|\%value="
egrep $str $input_file
So you can match the two criteria of you search
因此,您可以匹配搜索的两个条件
#1
2
Try this:
尝试这个:
grep -A1 "^%name=" $Input_file | grep -B1 "^%value=" | grep -v "^--"
#2
1
you cannot directly use your "pattern (str)" in awk. because awk default doesn't work in multi-line mode. However you could do this with awk:
你不能直接在awk中使用你的“pattern(str)”。因为awk默认在多行模式下不起作用。但是你可以用awk做到这一点:
awk '/^%name=/{n=$0;next}/^%value=/&&n{print n"\n"$0}{n=""}' file
with your example, the above one-liner outputs:
以你的例子,上面的单线输出:
%name=ABC
%value=123
%name=XYZ
%value=789
#3
0
You can use a different syntax in your $str variable, the '*' is useless in because you are searching a pattern not a literal value, for gawk I can't help sorry
你可以在你的$ str变量中使用不同的语法,'*'是无用的因为你正在搜索模式而不是文字值,因为gawk我不能抱歉
try this:
尝试这个:
str="\%name=|\%value="
egrep $str $input_file
So you can match the two criteria of you search
因此,您可以匹配搜索的两个条件