[英]Iterating over a string separated by unescaped characters only
说我有以下字符串:
var="One two three\ four five"
什么命令将具有以下代码:
for item in "$(operation on $var)"; do
echo "$item"
done
并产生以下输出:
One
two
three four
five
或者,我可以使用单引号在已经用双引号括起来的字符串输入上实现这一点吗? 也就是说,我能拥有这根绳子吗?
var="One two 'three four' five"
在上述条件下产生相同的输出?
您可以在perl
模式下使用gnu grep
:
var="One two three\ four five"
grep -oP '[^\s\\]+(\\.[^\s\\]+)*' <<< "$var"
正则表达式详细信息:
[^\\s\\\\]+
:任何非空白字符不是的匹配1+ \\
(
:开始组
\\\\.[^\\s\\\\]+
:匹配\\
后跟任何转义字符,后跟另一个包含1+非空格和非反斜杠字符的字符串。 )*
:结束组。 匹配此组的0或更多。 One
two
three\ four
five
这是相同grep
posix版本 :
grep -oE '[^\\[:blank:]]+(\\.[^\\[:blank:]]+)*' <<< "$var"
如果要在循环中循环遍历这些字符串:
while IFS= read -r str; do
echo "$str"
done < <(grep -oP '[^\s\\]+(\\.\S+)*' <<< "$var")
只是为了延伸anubhava对第一种情况( "\\ "
)的彻底回答,这是第二种情况( "' '"
)的答案:
echo "one two 'three four three and a half' five" |
grep -oE "('([^'[:blank:]]+ )+[^'[:blank:]]+'|[^'[:blank:]]+)"
输出:
one
two
'three four three and a half'
five
使用数组:
arr=(one two 'three four' five)
for item in "${arr[@]}" ; do
echo "$item"
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.