Мне нужно и Applescript заменить некоторый текст следующим образом:
Оригинальный текст:
string string string $ text1
string string string $ text2
text3
string string string $ text4
Требуемый результат:
$ text1
$ text2
text3
$ text4
Я могу сделать это в терминале с помощью этой команды:
$ echo "string string string $ text1
string string string $ text2
text3
string string string $ text4" | sed -r 's/^(.*)\$ ?(.) (.*)$/$ \3/g'
$ text1
$ text2
text3
$ text4
Кстати, я использую bash версии 4.3.30 и sed 4.2.2, оба из доморощенного.
Проблема здесь в том, что мне нужно сделать это из яблочного скрипта. Это мой подход:
set commandString to "echo \"string string string $ text\" | sed -r 's|^(.*)\\$ ?(.) (.*)$|$ \\3|g'" as string
set formattedCode to do shell script commandString
И я получаю следующую ошибку:
error "sed: illegal option -- r
usage: sed script [-Ealn] [-i extension] [file ...]
sed [-Ealn] [-i extension] [-e script] ... [-f script_file] ... [file ...]" number 1
Если я удалю эту -r
опцию, я получу другую ошибку:
sed: 1: "s|^(.*)\$ ?(.) (.*)$|$ ...": \3 not defined in the RE
Если я удалю \3
, вывод должен быть $
вместо $ text
, но sed
команда ничего не делает и выводит:
string string string $ text
Я предположил, что это может быть проблема с sed
версией. Итак, если я заменю sed
на /usr/local/bin/sed
это, после строки ничего не произойдет set formattedCode to do shell script commandString
.
Кто-то знает, где проблема?
Параметр -r GNU sed равен -E в OS X/BSD sed (тот, который поставляется с ОС, /usr/bin/sed
). А чтобы избавиться от проблемы кодировки с , добавьте export LC_ALL=en_US.UTF-8; export LANG=en_US.UTF-8;
в начало команды do shell script (см. вопрос здесь ):
set original_text to "string string string $ text1
string string string $ text2
text3
string string string $ text4"
set commandString to "export LC_ALL=en_US.UTF-8; export LANG=en_US.UTF-8; " & ¬
"echo " & quoted form of original_text & " | sed -E 's|^(.*)\\$ ?(.) (.*)$|$ \\3|g'" as string
set formattedCode to do shell script commandString
Возвращает:
$ text1
$ text2
text3
$ text4
set original_text to "string string string $ text1
string string string $ text2
text3
string string string $ text4"
set output to {}
set od to AppleScript's text item delimiters
set AppleScript's text item delimiters to {"
"}
set all_lines to every text item of original_text
repeat with the_line in all_lines
if "$" is not in the_line then
set output to output & the_line
else
set AppleScript's text item delimiters to {"$"}
set latter_part to last text item of the_line
set AppleScript's text item delimiters to {" "}
set last_word to last text item of latter_part
set output to output & ("$ " & last_word as string)
end if
end repeat
set AppleScript's text item delimiters to {"
"}
set output to output as string
set AppleScript's text item delimiters to od
return output
Возвращает:
$ text1
$ text2
text3
$ text4
-E
работу на терминале, но не на яблочном скрипте.
Маркханте