iUser iUser - 8 months ago 42
Bash Question

Bash Script to grep string in file and output to another file

I wrote a bash script to grep for a string and succeeding few lines and then output to another file.

Here is my bash script

#!/bin/bash

echo "$#"

if [ "$#" -ne 4 ]; then

echo "Usage : ./redirectTrace.sh searchText inputFile number_of_Lines_succeeding_the_searchText outputFile"

else

searchText=$0
inputFile=$1
lines=$2
outputFile=$3

echo "$0 , $2, $3, $4"

grep -i -A "$lines" "$searchText" $inputFile > $outputFile
fi


When I execute this as
./redirectTrace.sh Drag:: log/Test.log 10 Drag1.log
, I get

grep: log/Test.log: invalid context length argument


If I don't pass number of lines and execute with a fixed value, I get another error.

Script :

grep -i -A 10 "$searchText" $inputFile > $outputFile


Execution :
./redirectTrace.sh Drag:: log/Test.log Drag1.log`

I get following error :

grep: Drag::: No such file or directory


Also
log/Test.log
file becomes empty.

Why?

Answer

A major part is because $0 is the name of the script not the first argument to the script. The first argument is $1, the fourth argument is $4, etc.

So your assignments should be:

searchText=$1
inputFile=$2
lines=$3
outputFile=$4