简体   繁体   中英

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

#!/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. I would love your advice with detail

在此处输入图片说明

Spaces are required in the if command:

if [[ $rc != 0 ]]

You can also combine this with 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. You can't run everything together the way you've done. You also don't need the extra [ ] around the if statement.

#!/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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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