- Linux sed regexp example
- Изучаем команды Linux: sed
- 1. Введение
- 2. Установка
- 3. Концепции
- 4. Регулярные выражения
- Unix / Linux — Regular Expressions with SED
- Invoking sed
- The sed General Syntax
- Deleting All Lines with sed
- The sed Addresses
- The sed Address Ranges
- The Substitution Command
- Substitution Flags
- Using an Alternative String Separator
- Replacing with Empty Space
- Address Substitution
- The Matching Command
- Using Regular Expression
- Matching Characters
- Character Class Keywords
- Aampersand Referencing
- Using Multiple sed Commands
- Back References
Linux sed regexp example
To know how to use sed , people should understand regular expressions ( for short). A regular expression is a pattern that is matched against a subject string from left to right. Most characters are : they stand for themselves in a pattern, and match the corresponding characters in the subject. As a trivial example, the pattern
In most scripts, pattern space is initialized to the content of each line (see How sed works). So, it is a useful simplification to think of ^#include as matching only lines where ‘ #include ’ is the first thing on line—if there are spaces before, for example, the match fails. This simplification is valid as long as the original content of pattern space is not modified, for example with an s command.
A leading ^ reverses the meaning of list , so that it matches any single character not in list . To include ] in the list, make it the first character (after the ^ if needed), to include — in the list, make it the first or last; to include ^ put it after the first character.
The characters $ , * , . , [ , and \ are normally not special within list . For example, [\*] matches either ‘ \ ’ or ‘ * ’, because the \ is not special here. However, strings like [.ch.] , [=a=] , and [:space:] are special within list and represent collating symbols, equivalence classes, and character classes, respectively, and [ is therefore special within list when it is followed by . , = , or : . Also, when not in POSIXLY_CORRECT mode, special escapes like \n and \t are recognized within list . See Escapes.
regexp1 \| regexp2 Matches either regexp1 or regexp2 . Use parentheses to use complex alternative regular expressions. The matching process tries each alternative in turn, from left to right, and the first one that succeeds is used. It is a GNU extension.
regexp1 regexp2 Matches the concatenation of regexp1 and regexp2 . Concatenation binds more tightly than \| , ^ , and $ , but less tightly than the other regular expression operators.
\ digit Matches the digit -th \(. \) parenthesized subexpression in the regular expression. This is called a . Subexpressions are implicity numbered by counting occurrences of \( left-to-right.
\n Matches the newline character.
\ char Matches char , where char is one of $ , * , . , [ , \ , or ^ . Note that the only C-like backslash sequences that you can portably assume to be interpreted are \n and \\ ; in particular \t is not portable, and matches a ‘ t ’ under most implementations of sed , rather than a tab character.
Note that the regular expression matcher is greedy, i.e., matches are attempted from left to right and, if two or more matches are possible starting at the same character, it selects the longest.
Examples: ‘ abcdef ’ Matches ‘ abcdef ’.
‘ a*b ’ Matches zero or more ‘ a ’s followed by a single ‘ b ’. For example, ‘ b ’ or ‘ aaaaab ’.
‘ a\?b ’ Matches ‘ b ’ or ‘ ab ’.
‘ a\+b\+ ’ Matches one or more ‘ a ’s followed by one or more ‘ b ’s: ‘ ab ’ is the shortest possible match, but other examples are ‘ aaaab ’ or ‘ abbbbb ’ or ‘ aaaaaabbbbbbb ’.
‘ .* ’ ‘ .\+ ’ These two both match all the characters in a string; however, the first matches every string (including the empty string), while the second matches only strings containing at least one character.
‘ ^main.*(.*) ’ This matches a string starting with ‘ main ’, followed by an opening and closing parenthesis. The ‘ n ’, ‘ ( ’ and ‘ ) ’ need not be adjacent.
‘ ^# ’ This matches a string beginning with ‘ # ’.
‘ \\$ ’ This matches a string ending with a single backslash. The regexp contains two backslashes for escaping.
‘ \$ ’ Instead, this matches a string consisting of a single dollar sign, because it is escaped.
‘ [a-zA-Z0-9] ’ In the C locale, this matches any ASCII letters or digits.
‘ [^ tab ]\+ ’ (Here tab stands for a single tab character.) This matches a string of one or more characters, none of which is a space or a tab. Usually this means a word.
‘ ^\(.*\)\n\1$ ’ This matches a string consisting of two equal substrings separated by a newline.
‘ .\<9\>A$ ’ This matches nine characters followed by an ‘ A ’.
‘ ^.\<15\>A ’ This matches the start of a string that contains 16 characters, the last of which is an ‘ A ’.
Источник
Изучаем команды Linux: sed
Оригинал: Learning Linux Commands: sed
Автор: Rares Aioanei
Дата публикации: 19 ноября 2011 года
Перевод: А. Кривошей
Дата перевода: июль 2012 г.
Николай Игнатушко проверил на GNU sed version 4.2.1 в дистрибутиве Gentoo все команды, упомянутые в этой статье. Не все скрипты хорошо отрабатывали на версии GNU sed. Но дело касалось мелочей, которые исправлены. Только скрипт по замене hill на mountains пришлось существенно переделать.
1. Введение
Добро пожаловать во вторую часть нашей серии, которая посвящена sed, версии GNU. Существует несколько версий sed, которые доступны на разных платформах, но мы сфокусируемся на GNU sed версии 4.x. Многие из вас слышали о sed, или уже использовали его, скорее всего в качестве инструмента замены. Но это только одно из предназначений sed, и мы постараемся показать вам все аспекты использования этой утилиты. Его название расшифровывается как «Stream EDitor» и слово «stream» (поток) в данном случае может означать файл, канал, или просто stdin. Мы надеемся, что у вас уже есть базовые знания о Linux, а если вы уже работали с регулярными выражениями, или по крайней мере знаете, что это такое, то все для вас будет намного проще. Объем статьи не позволяет включить в нее полное руководство по регулярным выражениям, вместо этого мы озвучим базовые концепции и дадим большое количество примеров использования sed.
2. Установка
Здесь не нужно много рассказывать. Скорее все sed у вас уже установлен, так как он используется различными системными скриптами, а также пользователями Linux, которые хотят повысить эффективность своей работы. Вы можете узнать, какая версия sed у вас установлена, с помощью команды:
В моей системе эта команда показывает, что у меня установлен GNU sed 4.2.1 плюс дает ссылку на домашнюю страницу программы и другие полезные сведения. Пакет называется «sed» независимо от дистрибутива, кроме Gentoo, где он присутствует неявно.
3. Концепции
Перед тем, как идти дальше, мы считаем важным акцентировать внимание на том, что делает «sed», так как словосочетание «потоковый редактор» мало что говорит о его назначении. sed принимает на входе текст, выполняет заданные операции над каждой строкой (если не задано другое) и выводит модифицированный текст. Указанными операциями могут быть добавление, вставка, удаление или замена. Это не так просто, как выглядит: предупреждаю, что имеется большое количество опций и их комбинаций, которые могут сделать команду sed очень трудной для понимания. Поэтому мы рекомендуем вам изучить основы регулярных выражений, чтобы понимать, как это работает. Перед тем, как приступить к руководству, мы хотели бы поблагодарить Eric Pement и других за вдохновление и за то, что он сделал для всех, кто хочет изучать и использовать sed.
4. Регулярные выражения
Так как команды (скрипты) sed для многих остаются загадкой, мы чувствуем, что наши читатели должны понимать базовые концепции, а не слепо копировать и вставлять команды, значения которых они не понимают. Когда человек хочет понять, что представляют собой регулярные выражения, ключевым словом является «соответствие», или, точнее, «шаблон соответствия». Например, в отчете для своего департамента вы написали имя Nick, обращаясь к сетевому архитектору. Но Nick ушел, а на его место пришел John, поэтому теперь вы должны заменить слово Nick на John. Если файл с отчетом называется report.txt, вы должны выполнить следующую команду:
По умолчанию sed использует stdout, вы можете использовать оператор перенаправления вывода, как показано в примере выше. Это очень простой пример, но мы проиллюстрировали несколько моментов: мы ищем все соответствия шаблону «Nick» и заменяем во всех случаях на «John». Отметим, что sed призводит поиск с учетом регистра, поэтому будьте внимательны и проверьте выходной файл, чтобы убедиться, что все замены были выполнены. Приведенный выше пример можно было записать и так:
Хорошо, скажете вы, но где же здесь регулярные выражения? Да, мы хотели сначала показать пример, а теперь начинается самая интересная часть.
Если вы не уверены, написали ли вы «nick» или «Nick», и хотите предусмотреть оба случая, необходимо использовать команду sed ‘s/Nick|nick/John/g’. Вертикальная черта имеет значение, которое вы должны знать, если изучали C, то есть ваше выражение будет соответствовать «nick» или «Nick». Как вы увидите ниже, канал может использоваться и другими способами, но смысл остается тот же самый. Другие операторы, широко использующиеся в регулярных выражениях — это «?», который соответствует повторению предшествующего символа ноль или один раз (то есть flavou?r будет соответствовать flavor и flavour), «*» — ноль или более раз, «+» — один или более раз. «^» соответствует началу строки, а «$» — наоборот. Если вы — пользователь vi или vim, многие вещи покажутся вам знакомыми. В конце концов, эти утилиты, вместе с awk и С уходят корнями в ранние дни UNIX. Мы не будем больше говорить на эту тему, так как проще понять значение этих символов на примерах, но вы должны знать, что существуют различные реализации регулярных выражений: POSIX, POSIX Extended, Perl, а также различные реализации нечетких регулярных выражений, гарантирующие вам головную боль.
Источник
Unix / Linux — Regular Expressions with SED
In this chapter, we will discuss in detail about regular expressions with SED in Unix.
A regular expression is a string that can be used to describe several sequences of characters. Regular expressions are used by several different Unix commands, including ed, sed, awk, grep, and to a more limited extent, vi.
Here SED stands for stream editor. This stream-oriented editor was created exclusively for executing scripts. Thus, all the input you feed into it passes through and goes to STDOUT and it does not change the input file.
Invoking sed
Before we start, let us ensure we have a local copy of /etc/passwd text file to work with sed.
As mentioned previously, sed can be invoked by sending data through a pipe to it as follows −
The cat command dumps the contents of /etc/passwd to sed through the pipe into sed’s pattern space. The pattern space is the internal work buffer that sed uses for its operations.
The sed General Syntax
Following is the general syntax for sed −
Here, pattern is a regular expression, and action is one of the commands given in the following table. If pattern is omitted, action is performed for every line as we have seen above.
The slash character (/) that surrounds the pattern are required because they are used as delimiters.
Sr.No. | Range & Description | |||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 |
Sr.No. | Range & Description | ||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 |
Sr.No. | Flag & Description | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
1 |
Sr.No. | Character & Description | ||||||||
---|---|---|---|---|---|---|---|---|---|
1 |
Sr.No. | Expression & Description | |||||
---|---|---|---|---|---|---|
1 |
Sr.No. | Set & Description | ||
---|---|---|---|
1 |
Sr.No. | Character Class & Description |
---|---|
1 |