Bash:如果行以 > 开头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21858164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash: If line begins with >
提问by Stephopolis
I want an if
/then
statement in Bash and I can't seem to get it to work. I would like to say "If the line begins with >
character, then do this, else do something else".
我想要Bash 中的if
/then
语句,但似乎无法使其正常工作。我想说“如果该行以>
字符开头,则执行此操作,否则执行其他操作”。
I have:
我有:
while IFS= read -r line
do
if [[$line == ">"*]]
then
echo $line'first'
else
echo $line'second'
fi
done
But it isn't working. I also tried to escape the ">" by saying:
但它不起作用。我还试图通过说来逃避“>”:
if [[$line == ^\>*]]
Which didn't work either. Both ways I am getting this error:
这也不起作用。我收到此错误的两种方式:
line 27: [[>blah: command not found
Suggestions?
建议?
回答by anubhava
Spaces are needed inside [[ and ]]
as follows:
内部需要的空间[[ and ]]
如下:
if [[ "$line" == ">"* ]]; then
echo "found"
else
echo "not found"
fi
回答by hek2mgl
This attempt attempt uses a regex:
此尝试尝试使用正则表达式:
line="> line"
if [[ $line =~ ^\> ]] ; then
echo "found"
else
echo "not found"
fi
This one uses a glob pattern:
这个使用 glob 模式:
line="> line"
if [[ $line == \>* ]] ; then
echo "found"
else
echo "not found"
fi
回答by SylvainD
Spacing is important.
间距很重要。
$ [[ ">test" == ">"* ]]; echo $?
0
$ [[ "test" == ">"* ]]; echo $?
1
回答by Somya Arora
if grep -q '>' <<<$line; then
..
else
..
fi
using grep is much better :)
使用 grep 好多了:)