简体   繁体   中英

sed command doesn't work with open command

I use sed to replace character ~ in string, and then open the folder of the path shown by this string on macOS.

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

Echo can print the correct path /JKFolder/demo/ , but open can't, it seems to run the first part of the string, which is the same as open $string . Sed doesn't work in this command. Thank you.

When you omit echo the string variable is not passed to sed , hence it does not work.

This would work:

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

However, you do not really need sed in this case, you can just use

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

See this online demo .

The "${string/\~/\/JKFolder\/demo}" is an example of a variable expansion, where the first occurrence of a ~ char is replaced with /JKFolder/demo string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM