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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

@anubhava I don't generally try to race.
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
@Amber: Don't take it otherwise, all 3 of us answered pretty much same thing that's why I commented.
@Amber: I think I'll do it :)
@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).
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.

2 Comments

Thanks a lot for pointing this. So if I have no bash I can't use this condition?
Yes that's correct if you don't have BASH then you can't use =~ regex operator either.
1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.