Awk 使用少量值存储变量,并需要使用特定单词“grep”行;是”;在某个特定单词首次出现之后;完";
使用很少的值存储变量,并且需要用特定的单词“yes”grep行。但只需在某个特定单词首次出现后进行grep,例如“End” 考虑下面的变量值,它有下面的行Awk 使用少量值存储变量,并需要使用特定单词“grep”行;是”;在某个特定单词首次出现之后;完";,awk,sed,grep,Awk,Sed,Grep,使用很少的值存储变量,并且需要用特定的单词“yes”grep行。但只需在某个特定单词首次出现后进行grep,例如“End” 考虑下面的变量值,它有下面的行 one two three yes ------End------ wind tree fruits yes ------End------ hi hello yes 从变量中,需要grep在第一次出现单词End之后具有“yes”的所有行 预期产出: fruits yes
one
two
three yes
------End------
wind
tree
fruits yes
------End------
hi
hello yes
从变量中,需要grep在第一次出现单词End之后具有“yes”的所有行
预期产出:
fruits yes
hello yes
使用awk:
$ awk '/End/{p=1}p==1&&/yes/' file
fruits yes
hello yes
解释:
awk '
/End/ { p=1 } # the End set p flag to 1
p==1 && /yes/ # when p flag raised and at yes, output
' file
如果要在第二次
结束后打印,请使用GNUsed
将p=1
更改为p++
,并将比较p==1
更改为p>=2
:
$ sed -n '/End/,${/yes/p}' file
fruits yes
hello yes
如果变量中包含数据:
$ printf '%s\n' "$variable" | sed -n '/End/,${/yes/p}'
fruits yes
hello yes
$ new_variable=$(printf '%s\n' "$variable" | sed -n '/End/,${/yes/p}')
要将其保存在变量中,请执行以下操作:
$ printf '%s\n' "$variable" | sed -n '/End/,${/yes/p}'
fruits yes
hello yes
$ new_variable=$(printf '%s\n' "$variable" | sed -n '/End/,${/yes/p}')
sed
脚本将打印包含字符串yes
(带/yes/p
)的所有行,但仅打印第一次出现单词End
之后的行(范围为/End/,$
,即从包含End
的行到末尾).我只知道如何在文件中匹配后对所有行进行grep,但不确定如何在变量中首次出现匹配字后对所有行进行grep。需要从变量而不是从文件进行grep…您能否指导我使用与变量相关的命令,而不是使用文件echo“$var”| awk…