sed 如何替换“\” (反斜杠+空格)?
在 bash 脚本中,带有空格的文件显示为 "File\ with\spaces.txt"
,我想用 _
或 替换这些斜杠空格+。
我怎样才能告诉 sed 这样做呢?我没有成功使用;
$1=~/File\ with\ spaces.txt
ext=$1
web=$(echo "$ext" | sed 's/\ /+/')
如果有比 sed 更好的方法,我愿意接受建议。
[编辑]:Foo Bah 的解决方案效果很好,但它只替换了第一个空格,因为它后面的文本被视为参数而不是 $1 的一部分。有什么办法解决这个问题吗?
In a bash script, files with spaces show up as "File\ with\ spaces.txt"
and I want to substitute those slashed-spaces with either _
or +
.
How can I tell sed to do that? I had no success using;
$1=~/File\ with\ spaces.txt
ext=$1
web=$(echo "$ext" | sed 's/\ /+/')
I'm open to suggestions if there's a better way than through sed.
[EDIT]: Foo Bah's solution works well, but it substitutes only the first space because the text following it is treated as arguments rather than part of the $1. Any way around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
\\\\
在 shell 级别计算为\\
,然后在 sed 中计算为文字\
。\\\\
evaluates to a\\
at the shell level, and then into a literal\
within sed.Sed 可以很好地识别
\
:不过,您的 bash 脚本语法完全错误。
不确定您想对脚本做什么,但这里有一个用
+
替换空格的示例:更新:
哦,您需要 g 标志来替换所有出现的空格,而不仅仅是第一个。已修复如上。
Sed recognises
\
as space just fine:Your bash script syntax is all wrong, though.
Not sure what you were trying to do with the script, but here is an example of replacing spaces with
+
:Upd:
Oh, and you need the
g
flag to replace all occurences of space, not only the first one. Fixed above.你想逃避斜杠:
you want to escape the slash:
单引号是你的朋友
以下内容应与 $1 和 $2 的单引号参数一起使用
single quotes are your friend
the following should be used with single quoted args for $1 and $2