Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 带变量的Awk模式搜索_Bash_Variables_Awk_Pattern Matching - Fatal编程技术网

Bash 带变量的Awk模式搜索

Bash 带变量的Awk模式搜索,bash,variables,awk,pattern-matching,Bash,Variables,Awk,Pattern Matching,好的,我可以让一个变量传递到awk中,但当变量中有空格时,它不会搜索任何内容,所以这里有一些代码 new="bob" searc=`awk '/#'$new':/,/---/ {print $0}'` file.txt echo "$searc" 应该显示这样的内容 #bob: happy fun love sun ------ 因此,第一个示例^可以完美地工作,但是Luke Jackson现在从未被发现。将名称存储在变量中的原因是,它假设是动态的,因此

好的,我可以让一个变量传递到awk中,但当变量中有空格时,它不会搜索任何内容,所以这里有一些代码

 new="bob"
 searc=`awk '/#'$new':/,/---/ {print $0}'` file.txt
 echo "$searc"
应该显示这样的内容

  #bob:
   happy
   fun
   love
   sun
  ------
因此,第一个示例^可以完美地工作,但是Luke Jackson现在从未被发现。将名称存储在变量中的原因是,它假设是动态的,因此可以更改。现在我是错过了一些简单的事情,还是我不能这样做

 new="Luke Jackson"
 searc=`awk '/#'$new':/,/---/ {print $0}'` file.txt
 echo "$searc"

  #Luke Jackson:
   sad
   fun
   evil
   moon
  ------

如果你稍微重写一下脚本,就不会有任何问题

$ awk -v name='Luke Jackson' '$0~"#"name":"{f=1} f && /----/{f=0} f' file

  #Luke Jackson:
   sad
   fun
   evil
   moon

还请注意,可能需要精确匹配而不是模式匹配,在这种情况下,使用
=

简单sed也可以解决此问题:

new='Luke Jackson'
sed -n "/#$new:/,/---/p" file

#Luke Jackson:
sad
fun
evil
moon
------

使用双引号:
searc=`awk'/#'“$new”:/,/--/{print$0}'`file.txt
@anubhava这是一种习惯性的打字错误,变量应该是双引号,请更正text@JonathanLeffler嗯,这正是我错过的我不敢相信我没有看到,谢谢
-n
抑制正常输出,并且
/p
仅打印文件中选定的部分。我从来不知道我可以用sed实现这一点!谢谢如果成功了