почему это правда, что для замены SED необходимы три обратные косые черты на окнах

2060
panny

Обращаясь к этому вопросу:

Зачем \нужна дополнительная функция cmd.exeдля работы sed(MinGW msys-1.0), если \она не является специальным символом cmd /?(см. Последний абзац или здесь )?

Следующие специальные символы требуют кавычек: & <> [] {} ^ =; ! +, `~ [пробел]

Первая обратная косая черта ускользает от второй, лишая его особого значения. Дается две оставшиеся обратные косые черты, которые выходят за sedпределы третьей с помощью второй, поэтому в конце остается одна дословная обратная косая черта, что соответствует моему поиску и замене. Но все же я не удовлетворен этим объяснением, потому что:

cmd не выполняет токенизацию, поэтому первый шаг перехода не имеет смысла ... отсюда, \имеет только какое-то особое значение, когда предшествует "... так, каково реальное объяснение?

на Bash в Linux:

echo 'sample\input' | sed 's/\\/----/' sample----input 

на cmd.exeв Windows XP SP3 (не 'требуется):

echo sample\input | sed "s/\\/----/" sed: -e expression #1, char 9: unterminated 's' command  // for some reason sed received only one backslash which causes him trouble ?  echo sample\input | sed "s/\\\/----/" sample----input 
2

1 ответ на вопрос

3
barlop

Sed is doing it, it uses a regex in the "find" section. it uses BRE or ERE or PCRE depending on the switch. Backslash is special within a regex.

Added

I haven't used your version of using single quotes 'cos that makes no sense to me in cmd.exe!! cmd.exe uses double quotes if at all.

And it works fine.

tested with gnuwin32's sed run from cmd.exe as it is meant to be.

C:\>echo sample\input | sed "s/\\/----/" sample----input C:\>sed --v GNU sed version 4.2.1 Copyright (C) 2009 Free Software Foundation, Inc. 

If I was testing cygwin's sed i'd run it from the cygwin window as that's where cygwin programs are meant to be run. And then i'd use single quotes. msys seems similar to cygwin in that sense.

UPDATE

You can run cygwin's sed from cmd, or from cygwin. They behave different because they are different GNU versions, but I don't see any shell related issue running from cmd vs running from cygwin (other than the simple point about single quotes for cygwin 'cos eg bash, and double quotes for cmd).

And cygwin's is a much later version of sed. Gnuwin32's sed, like many gnuwin32 things including gnuwin32 grep, is years out of date. and e.g. later greps can fix bugs in earlier greps. The 2009 sed that gnuwin32 uses, or less up to date version that gnuwin32 uses, may be ok but may be better to use a recent version that cygwin would use.

Interestingly, the seds behave differently regarding backslash.. I can see how to get it working in the later sed, the sed that cygwin uses.

C:\blah>echo a\bc | c:\cygwin\bin\sed "s/\\/_/" /usr/bin/sed: -e expression #1, char 6: unterminated `s' command C:\blah>echo a\bc | c:\cygwin\bin\sed "s/\\\/_/" a_bc C:\blah>echo a\bc | "c:\Program Files (x86)\GnuWin32\bin\sed" "s/\\/_/" a_bc 

The earlier sed (gnuwin32's sed), allows "s/\/_/" It's not escaping the forward slash. So the backslash is escaping the backslash to make a literal backslash. And the forward slash after the two backslashes, remains fine. And it works in that.

note- running cygwin's sed in cmd is fine. And since it's a later version it's preferable to gnuwin32's sed.

The later sed (cygwin's sed), does not allow "s/\/_/" because the / is escaping the forward slash. Instinct(and correct instinct) would be try adding another backslash and see what happens. And it works. Not sure the mechanics but I guess a single backslash in the later sed is \\\.

C:\blah>echo \ | c:\cygwin\bin\sed "s/\\\/d/" d 
Я заметил, что мой ответ только частично объясняет вещи, поскольку он все еще не объясняет три. Почему не два barlop 11 лет назад 0
"windows" sed или "unix" sed или оба? panny 11 лет назад 0
@Panny не знаю, что он использует, или почему он использует одинарные кавычки в cmd. Но я попробовал версию его, с двойными кавычками, и она работала нормально, всего два обратных слеша. AH он использует msys по-видимому. barlop 11 лет назад 0
Если вы используете msys, я бы предложил использовать графический интерфейс mingw32, который я видел на скриншотах. Если вы хотите использовать cmd.exe, используйте порт win32. У Gnuwin32 есть порт windows sed. barlop 11 лет назад 0
@ Я стараюсь не смешивать вещи. Итак, вещи Cygwin, которые я использую в окне Cygwin в Windows. Если бы я использовал msys, я бы использовал его в окне mingw32. И вещи gnuwin32, которые я бы использовал в cmd.exe. Но если вы хотите смешивать вещи, я бы попробовал использовать двойные кавычки в cmd, как вы и предполагали в cmd. Но смешивание вещей кажется ненужным и может усложнить barlop 11 лет назад 1
спасибо за подсказку с `'` panny 11 лет назад 0
Вы абсолютно правы с не смешивая окна, спасибо за этот совет также! В каком окне вы выполнили строки в своем ответе? panny 11 лет назад 0
давайте [продолжим обсуждение в чате] (http://chat.stackexchange.com/rooms/7796/discussion-between-barlop-and-panny) barlop 11 лет назад 0
@panny (просто убедившись, что вы получили уведомление с моим ответом вам) barlop 8 лет назад 0