Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.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
String bash检查字符串是否包含空格_String_Bash - Fatal编程技术网

String bash检查字符串是否包含空格

String bash检查字符串是否包含空格,string,bash,String,Bash,在我的bash脚本中,我想检查字符串中是否包含空格,以及是否将字符串中的空格替换为%20,以将字符串解析为网站 我对bash很陌生,最好的方法是什么 我知道如何在c#中实现这一点,但我看到bash有点不同。在Debian和Ubuntu上,可以安装gridsite客户端软件包: sudo apt-get install gridsite-clients 此包附带一个名为urlencode的命令,该命令使用百分比编码对字符串进行编码。这超出了您的要求,因为例如百分比本身也被编码(到%25) 例如:

在我的bash脚本中,我想检查字符串中是否包含空格,以及是否将字符串中的空格替换为
%20
,以将字符串解析为网站

我对bash很陌生,最好的方法是什么


我知道如何在c#中实现这一点,但我看到bash有点不同。

在Debian和Ubuntu上,可以安装
gridsite客户端
软件包:

sudo apt-get install gridsite-clients
此包附带一个名为
urlencode
的命令,该命令使用百分比编码对字符串进行编码。这超出了您的要求,因为例如百分比本身也被编码(到
%25

例如:

$ urlencode "foo bar"
foo%20bar
$ urlencode "foo%bar"
foo%25bar
$ urlencode "foo-bar/baz"
foo-bar%2Fbaz

使用
sed
[在shell脚本中]很容易做到这一点:

#!/bin/bash -

str="abc def ghi"
echo "$str"

hstr=`echo "$str" | sed -e 's/ /%20/g'`
echo "$hstr"
请参阅bash手册中的“Shell参数扩展”

对于您的情况,假设一个名为x的变量

$ x="one two three"

$ echo $x
one two three

$ echo ${x// /%20}
one%20two%20three

(*编辑:链接到gnu.org bash手册)

替换空格,而不是字符串,我假定?仅替换空格(到
%20
)?请注意,对于百分比编码,还有其他字符也需要编码…是的,只有字符串中的空格。但这使您的编码成为一种方式,因为如果原始字符串说“我得到了20%20”,它将编码为
I%20get%2020%20
,并且您无法知道最后一个
%20
的来源。是的,但对于我来说(denon接收器上的请求输入模式),这很好。