Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

3 Answers 3

up vote 2 down vote accepted

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.

share|improve this answer
    
Thanks a lot for pointing this. So if I have no bash I can't use this condition? –  P.S. Oct 30 '13 at 17:36
1  
Yes that's correct if you don't have BASH then you can't use =~ regex operator either. –  anubhava Oct 30 '13 at 17:37
    
Thanks !! Now all clear! –  P.S. Oct 30 '13 at 17:39
    
You're welcome, if you are satisfied please mark the answer as accepted. –  anubhava Oct 30 '13 at 17:46

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

share|improve this answer
1  
Just 23 seconds :) –  anubhava Oct 30 '13 at 17:35
    
@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
    
@P.S. You can call shell commands from awk as well. :) –  Amber Oct 30 '13 at 17:51

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

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.