【问题标题】:sed command doesn't work with open commandsed 命令不适用于 open 命令
【发布时间】:2021-06-17 14:12:06
【问题描述】:

我用sed替换字符串中的character~,然后在macOS上打开这个字符串所示路径的文件夹。

#!/bin/bash
string="~/example"
echo $string | sed -r 's/~/\/JKFolder\/demo/'
open $string | sed -r 's/~/\/JKFolder\/demo/'

Echo可以打印出正确的路径/JKFolder/demo/,但是open不行,好像跑了字符串的第一部分,和open $string一样。 Sed 在此命令中不起作用。谢谢。

【问题讨论】:

  • 因为你省略了echo。你需要open $(sed -r 's/~/\/JKFolder\/demo/' <<< "$string")。或者,open "${string/\~/\/JKFolder\/demo}",这里不需要使用 sed。

标签: bash macos shell sed


【解决方案1】:

当您省略 echo 时,string 变量不会传递给 sed,因此它不起作用。

这可行:

open $(sed 's/~/\/JKFolder\/demo/' <<< "$string")
open $(echo "$string" | sed 's/~/\/JKFolder\/demo/')
open $(echo "$string" | sed 's,~,/JKFolder/demo,')

但是,在这种情况下,你并不需要sed,你可以直接使用

open "${string/\~/\/JKFolder\/demo}"

this online demo

"${string/\~/\/JKFolder\/demo}" 是变量扩展的示例,其中~ 字符的第一次出现被/JKFolder/demo 字符串替换。

【讨论】:

    猜你喜欢
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    • 2023-03-30
    • 1970-01-01
    • 2019-09-19
    • 1970-01-01
    相关资源
    最近更新 更多