简体   繁体   English

如何列出文件并匹配bash脚本中的第一行?

[英]How to list files and match first line in bash script?

I would like to check for (only) python files for those which do not have the #!/usr/bin/env python in the first line. 我想检查第一行中没有#!/usr/bin/env python (仅)python文件。 So, I write a bash script that does the following: 因此,我编写了一个执行以下操作的bash脚本:

#!/bin/bash

#list all of python files

for file in `find . -name "*.py"`
do
        if [ `head -1 $file` != "#!/usr/bin/env python"] then;
                 echo "no match in file $file"
        else then;
                 echo "match!"
        fi
done

However, for some reason I cannot get the if statement correct! 但是,由于某种原因,我无法获得正确的if语句! I've looked at many questions, but I cannot find one that succinctly describes the issue. 我看过很多问题,但是找不到一个简洁地描述问题的问题。 Here is the error message: 这是错误消息:

./run_test.sh: line 9: syntax error near unexpected token `else'
./run_test.sh: line 9: `    else then;'

where am I going awry? 我要去哪里了? Thank you. 谢谢。

You can do something like 你可以做类似的事情

find . -type f -name '*.py' -exec \
  awk 'NR==1 && /#!\/usr\/bin\/env python/ \
  { print "Match in file " FILENAME; exit } \
  { print "No match in file " FILENAME; exit }' \
{} \;

If you are going to loop over it, don't use a for loop 如果要循环遍历, 请不要使用for循环

#!/bin/bash
find . -type f -name '*.py' -print0 | while IFS= read -r -d $'\0' file; do
  if [[ $(head -n1 "$file") == "#!/usr/bin/env python" ]]; then
      echo "Match in file [$file]"
  else
      echo "No match in file [$file]"
  fi
done

Things to notice: 注意事项:

  1. The [] after your if statement needs correct spacing if语句后的[]需要正确的空格
  2. The ';' ';' (if you enter a new line is not necessary) goes after the if and not after the then (如果您没有输入新行)则在if之后, 然后then之后
  3. You added an extra then after the else. 您添加了一个额外别的了。

     #!/bin/bash #list all of python files for file in `find . -name "*.py"` do if [ `head -1 $file` != "#!/usr/bin/env python" ]; then echo "no match in file $file" else echo "match!" fi done 

can you use -exec option by any chance? 您可以使用-exec选项吗? I find it easier. 我觉得比较容易。

find . -name "*.py" -exec head -1 {} | grep -H '#!/usr/bin/env python' \;

You can control the output using grep options. 您可以使用grep选项控制输出。


edit 编辑

Thanks to @chepner - To avoid the pipe being swallowed too early: 感谢@chepner-为避免过早吞咽管道:

-exec sh -c "head -1 {} | grep -H '#!/usr/bin/env python'" \;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM