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?
[[ expr ]] is a bash-ism; sh doesn't have it.
Use #!/bin/bash if you want to use that syntax.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With