bash 字符串不为空时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21528482/
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 while string is not empty
提问by dreadiscool
I'm trying to set up a script that parses a string.
我正在尝试设置一个解析字符串的脚本。
My loop is currently
我的循环目前是
while [ -n "$RAW" ]; do
// do some processing here
RAW=$(echo $RAW| sed -r 's/^.{15}//')
done
However, the script never seems to end
然而,剧本似乎永远不会结束
回答by perreal
It is not ending because the sed
expression is not correct. It expects minimum 15 characters and does not work for anything less than 15 chars. Try this:
它没有结束,因为sed
表达方式不正确。它需要最少 15 个字符,并且不适用于少于 15 个字符的任何字符。尝试这个:
RAW=$(echo $RAW| sed -r 's/^.{0,15}//')
回答by Mark Setchell
Maybe you just want this:
也许你只是想要这个:
#!/bin/bash
RAW=012345678901234567890
.
.
.
RAW=${RAW:15}
echo $RAW
567890
回答by anubhava
It might not end because of the logic inside your while loop.
由于 while 循环中的逻辑,它可能不会结束。
You're doing to overwrite variable RAW
:
你正在做覆盖变量RAW
:
RAW=$(echo $RAW| sed -r 's/^.{15}//')
Which means match and replace first 15 characters in original variable by empty string. What is there are only 10 characters left. In that sed won't match (and replace) and your varialbe RAW
will remain at that value.
这意味着用空字符串匹配并替换原始变量中的前 15 个字符。只剩下10个字符是什么。在那个 sed 将不匹配(并替换)并且您的变量RAW
将保持在该值。
You probably want upto 15 characters from startto be replaced and if that's the case this is what you will need:
您可能希望从一开始就最多替换15 个字符,如果是这种情况,这就是您需要的:
RAW=$(echo $RAW | sed -r 's/^.{1,15}//')