Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
检查while循环(shell)中的regexp条件_Regex_Shell_Loops_If Statement_While Loop - Fatal编程技术网

检查while循环(shell)中的regexp条件

检查while循环(shell)中的regexp条件,regex,shell,loops,if-statement,while-loop,Regex,Shell,Loops,If Statement,While Loop,我在运行我的简单shell脚本时遇到问题,我使用while循环读取文本文件,并尝试使用匹配的regexp检查条件: #!/bin/sh regex="^sometext" cat input.txt | { while read string do if [[ $string ~= $regex ]]; then echo "$string" | awk '{print $1}' >> output.txt else

我在运行我的简单shell脚本时遇到问题,我使用while循环读取文本文件,并尝试使用匹配的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
}
但我只会犯这样的错误

[[: not found

您能告诉我吗?

因为您正在使用shebang来表示
/bin/sh
[[
仅在BASH中可用

将shebang更改为
/bin/bash


顺便说一句,你的脚本完全可以用简单的awk来处理,你不需要在
中使用
awk
,而在这里循环

[[expr]]]
是一个bash-ism;sh没有它

如果要使用该语法,请使用
#!/bin/bash


也就是说,为什么要使用shell脚本? Awk已经可以完成您在这里所做的一切-您只需利用Awk内置的正则表达式匹配和每行执行多个操作的能力:

您的原始脚本可以简化为以下命令:

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

如果模式匹配,Awk将运行第一个
{}
-块,该块执行
打印$1
,然后强制Awk移动到下一行。否则,它将继续运行到第二个
{}
-block,它只打印行。

sh
不支持双括号语法-这是显式的
bash
-ism


尝试将shebang行更改为
#!/bin/bash

非常感谢您指出这一点。因此,如果我没有bash,我就不能使用此条件?是的,如果您没有bash,这是正确的,那么您也不能使用
=~
正则表达式操作符。@anubhava我通常不会尝试比赛。谢谢您的评论!我简化了我的脚本以在这里发布。Fu检查条件后的ll命令是
echo“$string”| awk'{print$1}“| base64-d | iconv-f UTF-8-t KOI8-R>>outfile.txt
@Amber:别这么认为,我们三个人的回答都差不多,这就是我发表评论的原因。@Amber:我想我会这么做的:)@P.s.一种简化的方法是制作一个shell脚本,只执行您想在特定行上执行的命令链,然后使用awk来调用只为相关行创建shell脚本-
{print$1 |“myscript.sh”;close(“myscript.sh”);next}
(close确保脚本的输出在任何下一个打印行之前)。