0

I am iterating through a text file line by line in bash and printing out the word segments that match the relevant regex pattern. This process is done by accepting the text file as an argument. My code works fine but at the end, in the last line, an unwanted output gets printed. I am new to bash and I have no idea why this is happening. Shown below is my code:

#!/bin/bash
pat='[a-z][a-zA-Z0-9_]*\.png'
while IFS='' read -r line || [[ -n $line ]];do
   echo $line | grep -o -P $pat
done < "$1"

shown below is the output(the unwanted line is the highlighted one):

enter image description here

I want to get rid of this last line of unwanted output.

Yushin
  • 1,684
  • 3
  • 20
  • 36
Suleka_28
  • 2,761
  • 4
  • 27
  • 43

1 Answers1

0

The problem is that you're running the script with sh instead of bash. [[ is a bash extension, it's not available in sh. So change

sh test2.sh summary.md

to

bash test2.sh summary.md

Or, since the script starts with #!/bin/bash, just use:

./test.sh summary.md

You should also quote all the variables in the script. See I just assigned a variable, but echo $variable shows something else

Barmar
  • 741,623
  • 53
  • 500
  • 612