3

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?

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
P.S.
  • 33
  • 3

3 Answers3

3

[[ 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.

Community
  • 1
  • 1
Amber
  • 507,862
  • 82
  • 626
  • 550
  • @anubhava I don't generally try to race. – Amber Oct 30 '13 at 17:46
  • Thanks for comment! I simplified my script a bit to post here. Full command after checking condition is `echo "$string" | awk '{print $1}' | base64 -d | iconv -f UTF-8 -t KOI8-R >> outfile.txt` – P.S. Oct 30 '13 at 17:47
  • @Amber: Don't take it otherwise, all 3 of us answered pretty much same thing that's why I commented. – anubhava Oct 30 '13 at 17:48
  • @Amber: I think I'll do it :) – P.S. Oct 30 '13 at 17:53
  • @P.S. One way to simplify would make to make a shell script that just does the chain of commands you want to do on a particular line, and then use awk to invoke the shell script for only the relevant lines - `{print $1 | "myscript.sh"; close("myscript.sh"); next}` (the close ensures that the output from the script comes before any next printed line). – Amber Oct 30 '13 at 17:55
2

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.

anubhava
  • 761,203
  • 64
  • 569
  • 643
1

sh does not support the double bracket syntax - that's explicitly a bash-ism.

Try changing your shebang line to #!/bin/bash

Mikey T.K.
  • 1,112
  • 18
  • 43