简体   繁体   English

我正在尝试使用 Grep 命令在 txt 文件中查找命令字符串,然后编写脚本来计算每个文件中的行数

[英]I am trying to Grep a command to find a string of command in a txt file, then write a script to count the lines in each file

Here is my script below to automate it but i continue to get errors by the then, else, and fi areas where they are highlighted in red下面是我的脚本来自动化它,但我继续在 then、else 和 fi 区域出现错误,它们以红色突出显示

#!/bin/bash
grep $1 $2
rc=$?
if[[$rc!=0]]
then
echo "specified string $1 not present in $2"
else
echo "specified string $1 is present in the file $2"
fi
# number of lines of in a file
wc -l | $2 | awk '{print $1}'

Below is an better visual on the left side is my list of text to grep from and my right side is my script.下面是更好的视觉效果,左侧是我要 grep 的文本列表,右侧是我的脚本。 I would love your advice with detail我希望得到你的详细建议

在此处输入图片说明

Spaces are required in the if command: if命令中需要空格:

if [[ $rc != 0 ]]

You can also combine this with grep :您还可以将其与grep结合使用:

if grep "$1" "$2"
then
...

You've got the basic syntax down.您已经掌握了基本语法。 What's wrong is that bash is really finicky about spaces between each of the sections of the if statement.问题在于 bash 对 if 语句的每个部分之间的空格非常挑剔。 You can't run everything together the way you've done.你不能像你所做的那样一起运行所有东西。 You also don't need the extra [ ] around the if statement.您也不需要 if 语句周围的额外 []。

#!/bin/bash
grep $1 $2
rc=$?

if [ $rc != 0 ]
then
  echo "specified string $1 not present in $2"
else
  echo "specified string $1 is present in the file $2"
fi

# number of lines of in a file
wc -l $2 | awk '{print $1}'

You also had an extra |你还有一个额外的| in the last line.在最后一行。

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

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