Home  >  Article  >  Operation and Maintenance  >  The most commonly used set of "Sed" techniques in Linux production environments

The most commonly used set of "Sed" techniques in Linux production environments

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼forward
2019-08-23 17:55:392117browse

The most commonly used set of

The sed command is widely used and easy to use. It is a powerful tool for rapid text processing. In fact, it doesn’t have many skills. Memorizing and using it are the most suitable learning channels, and it is a hard skill. But it's complicated because there are so many advanced features. This article does not focus on the advanced functions of sed, but only explains some commonly used operations.

As you use it, you will find that it is consistent with some concepts of vim. The syntax of regular expressions is basically the same, and there is not much learning cost. From the perspective of personal vision and work efficiency, the sed command is an important tool that programmers must master.

Those who say that they can use Google on the spot are mostly used to copying the text into Excel, slowly working on it, and they are even more confused when encountering a large number of files. It doesn’t mean that one family does not enter the other. This article is not written for you.

A simple introduction

The most commonly used set of Sed techniques in Linux production environments

As shown in the figure, a simple sed command contains three main parts: parameters, range, and operation . The file to be operated can be directly hung at the end of the command line. In addition to the command line, sed can also specify a sed script through the -f parameter. This is an advanced usage and will not be described in too much.

Related recommendations: "linux tutorial"

I will repeat some example commands many times. If you are smart, you will definitely find the rules, and sometimes you don't even need to explain.

Parameters

-n This parameter means --quiet or --silent. Indicates that the output of the execution process is ignored and only our results are output.

There is another parameter we commonly use: -i.

After using this parameter, all changes will be performed on the original file. Your output will overwrite the original file. Very dangerous, so be careful.

Range

1,4 means to find the contents of lines 1, 2, 3, and 4 in the file.

The designation of this range is very spiritual. Please see the following example (please replace the range part in the picture by yourself).

The most commonly used set of Sed techniques in Linux production environments

Range selection can also use regular matching. See the example below.

The most commonly used set of Sed techniques in Linux production environments

#For the sake of intuition, the following commands correspond to the above introduction one by one. There can be spaces between the range and the operation.

The most commonly used set of Sed techniques in Linux production environments

Operation

The most commonly used operation is p, which means printing. For example, the following two commands are equivalent:

The most commonly used set of Sed techniques in Linux production environments

In addition to printing, there are also the following operations, which we commonly use.

The most commonly used set of Sed techniques in Linux production environments

Although operations such as a, i, c are basic but rarely used, they will not be introduced. We still use some commands to illustrate.

The most commonly used set of Sed techniques in Linux production environments

Let’s take a look at what the sed command can do, and click on the command to experience it.

Delete all lines starting with # and blank lines.

The most commonly used set of Sed techniques in Linux production environments

The most commonly used ones, such as the one below.

The most commonly used set of Sed techniques in Linux production environments

means printing the second line in the group file.

The most commonly used set of Sed techniques in Linux production environments

So what should I do if I want to execute multiple commands at once and don’t want to write a sed script file? Then I need to add the -e parameter.

The unit of operation of sed is a line.

Replacement mode

The above are the common matching modes of the sed command, but it also has a powerful replacement mode, which means to find and replace certain values ​​in it, and Output results. The -n parameter is rarely used when using replacement mode.

The most commonly used set of Sed techniques in Linux production environments

The replacement mode has a lot of parameters, but the first and fifth parts can be omitted. After replacement, the entire text will be output.

The first half is used to match some ranges, while the second half performs the replacement action.

Scope

This range is similar to the range syntax above. See the example below.

The most commonly used set of Sed techniques in Linux production environments

The specific command is:

The most commonly used set of Sed techniques in Linux production environments

Command

Команда здесь относится к s. Вот что значит замена.

Найти совпадения

Часть поиска найдет строку, которую нужно заменить. Эта часть может принимать чистые строки или регулярные выражения. См. пример ниже.

The most commonly used set of Sed techniques in Linux production environments

Команда аналогичная:

The most commonly used set of Sed techniques in Linux production environments

# Заменить

Пришло время чтобы найти Исходящая строка была заменена. Содержимое этого раздела заменяет содержимое раздела «Найти совпадения».

К сожалению, в этой части нельзя использовать регулярные выражения. Наиболее часто используется точная замена. Например, замените a на b.

Но есть и расширенные функции. Подобно обычному API Java или Python, замена sed также имеет значение Matched Pattern, и Group тоже можно получить, не вдаваясь в подробности. Обычно используемые символы замены. Нет, повторите еще раз. При использовании в строке замены она представляет исходные данные соответствия поиска.

The most commonly used set of Sed techniques in Linux production environments

Следующая команда заключит каждую строку в файле в кавычки. The most commonly used set of Sed techniques in Linux production environments

##flag параметр

Эти параметры можно использовать по отдельности или в нескольких вариантах. Представлены только наиболее часто используемые из них.

The most commonly used set of Sed techniques in Linux production environments

Посмотрите на синтаксис двух команд:

The most commonly used set of Sed techniques in Linux production environments

Из-за регулярности многие символы необходимо экранировать. В сценарии вы будете выполнять множество операций \\, \* и других операций. Вместо \ можно использовать четыре символа |^@!.

Например, следующие пять команд одинаковы.

The most commonly used set of Sed techniques in Linux production environments

Примечание. Этот метод нельзя использовать для первой половины диапазона. Я привык использовать символ @.

Другие

Регулярное выражение

Как видите, регулярные выражения встречаются повсюду в командной строке. Ниже приводится краткое объяснение.

The most commonly used set of Sed techniques in Linux production environments

##Параметр i

Параметр i был кратко представлен выше. Его функция заключается в том, чтобы разрешить выполнение операции на исходный файл. Независимо от того, что вы делаете, исходный файл будет перезаписан. Это очень опасно.

Добавив параметр, можно создать резервную копию исходного файла.

sed -i.bak 's/a/b/' file

Приведенная выше команда подействует на исходный файл file и создаст файл file.bak. Настоятельно рекомендуется использовать параметр i, чтобы также указать файл bak.

Мы используем две команды, чтобы оценить возможности sed в сочетании с другими командами.

Выводить строки длиной не менее 50 символов

The most commonly used set of Sed techniques in Linux production environments

Статистика того, сколько раз каждое слово встречается в файле

The most commonly used set of Sed techniques in Linux production environments

Найдите файл py в каталоге и удалите все комментарии на уровне строки

The most commonly used set of Sed techniques in Linux production environments

Посмотрите на строки 5-7 и 10-13

The most commonly used set of Sed techniques in Linux production environments

Выводить только IP-адрес

The most commonly used set of Sed techniques in Linux production environments

The above is the detailed content of The most commonly used set of "Sed" techniques in Linux production environments. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jianshu.com. If there is any infringement, please contact admin@php.cn delete