Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check regexp condition inside while loop (shell)

I have problem with running my simple shell script, where I am using while loop to read text file and trying to check condition with matching regexp:

#!/bin/sh
regex="^sometext"


cat input.txt | 
{
  while read string
    do if [[ $string ~= $regex ]]; then
            echo "$string" | awk '{print $1}' >> output.txt
       else
            echo "$string" >> outfile.txt
       fi
    done
}

but I recieve only errors like

[[: not found

could you please advise me?

like image 401
P.S. Avatar asked Mar 03 '26 11:03

P.S.


2 Answers

[[ expr ]] is a bash-ism; sh doesn't have it.

Use #!/bin/bash if you want to use that syntax.


That said, why use a shell script?

Awk can already do everything you're doing here - you just need to take advantage of Awk's built-in regex matching and the ability to have multiple actions per line:

Your original script can be reduced to this command:

awk '/^sometext/ {print $1; next} {print}' input.txt >> output.txt

If the pattern matches, Awk will run the first {}-block, which does a print $1 and then forces Awk to move to the next line. Otherwise, it'll continue on to the second {}-block, which just prints the line.

like image 66
Amber Avatar answered Mar 06 '26 03:03

Amber


Because you're using shebang for /bin/sh and [[ is only available in BASH.

Change shebang to /bin/bash

btw your script can be totally handled in simple awk and you don't need to use awk inside the while loop here.

like image 36
anubhava Avatar answered Mar 06 '26 02:03

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!