Вопрос

I am creating an automator process but I need to take string and replace all the "\" characters with the character "/". Working with a buddy we decided to use a shell script but I am open to anything to do this. With the line we wrote, we just get an error.

set input to (do shell script "echo \"" & input & "\" | sed 's/\\\\//g'")

Thanks

Это было полезно?

Решение

Try:

set myString to "This\\is\\my\\string" -- really This\is\my\string

set {TID, text item delimiters} to {text item delimiters, "\\"}
set myString to text items of myString
set text item delimiters to "/"
set myString to myString as text
set text item delimiters to TID

return myString

or

set input to "This\\is\\my\\string" -- really This\is\my\string
set output to do shell script "echo " & quoted form of input & " | sed 's/[\\]/\\//g'"

Другие советы

As far as I know, it is no longer necessary to restore text item delimiters, so adayzdone's example can be simplified to something like this:

set s to "aa\\bb\\cc"
set text item delimiters to "\\"
set ti to text items of s
set text item delimiters to "/"
ti as text -- "aa/bb/cc"

do shell script uses /bin/sh, which is a version of bash that starts in POSIX mode and has a few other changes as well. One of them is that xpg_echo is enabled by default, so that echo interprets escape sequences like \t:

do shell script "echo " & quoted form of "ss\\tt" & " | xxd -p" -- "737309740a"

You can just use printf %s instead:

do shell script "printf %s " & quoted form of "ss\\tt" & "|tr \\\\ /" -- "s/t"

If you don't add a without altering line endings specifier, do shell script converts line endings to CR and chomps one newline from the end of the output.

@Lauri Ranta's do shell script pointers are helpful, but a simple variation of the original command does the trick:

Even though do shell script invokes bash as sh and therefore in a mode it calls 'POSIX mode', many bash-specific features are still available, among them the so called here-string to feed a string directly to a command via stdin, e.g.: cat <<<'Print this':

Thus, by using a here-string - passed with quoted form of from AppleScript, which is always advisable - the echo problem is bypassed:

# Sample input.
set input to "a\\\\b" # equivalent of" 'a\\b'

# Remove all `\` characters; returns 'ab'
set input to (do shell script "sed 's/\\\\//g' <<<" & quoted form of input)

Alternative, using tr -d instead of sed:

 set input to (do shell script "tr -d '\\\\' <<<" & quoted form of input)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top