Replace with sed linux

Содержание
  1. How to use sed to find and replace text in files in Linux / Unix shell
  2. Find and replace text within a file using sed command
  3. Syntax: sed find and replace text
  4. Examples that use sed to find and replace
  5. sed command problems
  6. How to use sed to match word and perform find and replace
  7. Recap and conclusion – Using sed to find and replace text in given files
  8. Как использовать sed для поиска и замены строки в файлах
  9. Найти и заменить строку с помощью sed
  10. Рекурсивный поиск и замена
  11. Выводы
  12. How to Find and Replace a String in File Using the sed Command in Linux
  13. What is sed Command
  14. 1) How to Find and Replace the “first” Event of the Pattern on a Line
  15. 2) How to Find and Replace the “Nth” Occurrence of the Pattern on a Line
  16. 3) How to Search and Replace all Instances of the Pattern in a Line
  17. 4) How to Find and Replace the Pattern for all Instances in a Line from the “Nth” Event
  18. 5) Search and Replace the pattern on a specific line number
  19. 6) How to Find and Replace Pattern in a Range of Lines
  20. 7) How to Find and Change the pattern in the Last Line
  21. 8) How to Find and Replace the Pattern with only Right Word in a Line
  22. 9) How to Search and Replaces the pattern with case insensitive
  23. 10) How to Find and Replace a String that Contains the Delimiter Character
  24. 11) How to Find and Replaces Digits with a Given Pattern
  25. 12) How to Find and Replace only two Digit Numbers with Pattern
  26. 13) How to Print only Replaced Lines with the sed Command
  27. 14) How to Run Multiple sed Commands at Once
  28. 15) How to Find and Replace the Entire Line if the Given Pattern Matches
  29. 16) How to Search and Replace lines that Matches a Pattern

How to use sed to find and replace text in files in Linux / Unix shell

Find and replace text within a file using sed command

The procedure to change the text in files under Linux/Unix using sed:

  1. Use Stream EDitor (sed) as follows:
  2. sed -i ‘s/old-text/new-text/g’ input.txt
  3. The s is the substitute command of sed for find and replace
  4. It tells sed to find all occurrences of ‘old-text’ and replace with ‘new-text’ in a file named input.txt
  5. Verify that file has been updated:
  6. more input.txt

Let us see syntax and usage in details.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements sed utility on Linux, macOS or Unix-like OS
Est. reading time 4 minutes

Syntax: sed find and replace text

The syntax is:
sed ‘s/word1/word2/g’ input.file
## *bsd/macos sed syntax#
sed ‘s/word1/word2/g’ input.file > output.file
sed -i ‘s/word1/word2/g’ input.file
sed -i -e ‘s/word1/word2/g’ -e ‘s/xx/yy/g’ input.file
## use + separator instead of / ##
sed -i ‘s+regex+new-text+g’ file.txt
The above replace all occurrences of characters in word1 in the pattern space with the corresponding characters from word2.

Examples that use sed to find and replace

Let us create a text file called hello.txt as follows:
$ cat hello.txt
The is a test file created by nixCrft for demo purpose.
foo is good.
Foo is nice.
I love FOO.

I am going to use s/ for substitute the found expression foo with bar as follows:
sed ‘s/foo/bar/g’ hello.txt
Sample outputs:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Please note that the BSD implementation of sed (FreeBSD/MacOS and co) does NOT support case-insensitive matching. You need to install gnu sed. Run the following command on Apple Mac OS:
$ brew install gnu-sed
######################################
### now use gsed command as follows ##
######################################
$ gsed -i ‘s/foo/bar/g I ‘ hello.txt
$ cat hello.txt

sed command problems

Consider the following text file:
$ cat input.txt
http:// is outdate.
Consider using https:// for all your needs.

Find word ‘http://’ and replace with ‘https://www.cyberciti.biz’:
sed ‘s/ http:// / https://www.cyberciti.biz /g’ input.txt
You will get an error that read as follows:

Our syntax is correct but the / delimiter character is also part of word1 and word2 in above example. Sed command allows you to change the delimiter / to something else. So I am going to use +:
sed ‘s+ http:// + https://www.cyberciti.biz +g’ input.txt
Sample outputs:

How to use sed to match word and perform find and replace

In this example only find word ‘love’ and replace it with ‘sick’ if line content a specific string such as FOO:
sed -i -e ‘/FOO/s/love/sick/’ input.txt
Use cat command to verify new changes:
cat input.txt

Recap and conclusion – Using sed to find and replace text in given files

The general syntax is as follows:
## find word1 and replace with word2 using sed ##
sed -i ‘s/word1/word2/g’ input
## you can change the delimiter to keep syntax simple ##
sed -i ‘s+word1+word2+g’ input
sed -i ‘s_word1_word2_g’ input
## you can add I option to GNU sed to case insensitive search ##
sed -i ‘s/word1/word2/gI’ input
sed -i ‘s_word1_word2_gI’ input

See BSD(used on macOS too) sed or GNU sed man page by typing the following command:
man sed

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Как использовать sed для поиска и замены строки в файлах

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

sed является s Tream ред itor. Он может выполнять базовые операции с текстом над файлами и входными потоками, такими как конвейеры. С помощью sed вы можете искать, находить и заменять, вставлять и удалять слова и строки. Он поддерживает базовые и расширенные регулярные выражения, которые позволяют сопоставлять сложные шаблоны.

В этой статье мы поговорим о том, как найти и заменить строки с помощью sed . Мы также покажем вам, как выполнить рекурсивный поиск и замену.

Найти и заменить строку с помощью sed

Существует несколько версий sed с некоторыми функциональными различиями. macOS использует версию BSD, в то время как большинство дистрибутивов Linux поставляются с предустановленной по умолчанию GNU sed . Мы будем использовать версию GNU.

Общая форма поиска и замены текста с помощью sed имеет следующий вид:

  • -i — По умолчанию sed записывает свой вывод в стандартный вывод. Эта опция указывает sed редактировать файлы на месте. Если указано расширение (например, -i.bak), создается резервная копия исходного файла.
  • s — Заменяющая команда, вероятно, наиболее часто используемая команда в sed.
  • / / / — Символ-разделитель. Это может быть любой символ, но обычно используется символ косой черты ( / ).
  • SEARCH_REGEX — обычная строка или регулярное выражение для поиска.
  • REPLACEMENT — строка замены.
  • g — Флаг глобальной замены. По умолчанию sed читает файл построчно и изменяет только первое вхождение SEARCH_REGEX в строке. Если указан флаг замены, заменяются все вхождения.
  • INPUTFILE — имя файла, для которого вы хотите запустить команду.

Рекомендуется заключать аргумент в кавычки, чтобы метасимволы оболочки не расширялись.

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

В демонстрационных целях мы будем использовать следующий файл:

Если флаг g опущен, заменяется только первый экземпляр строки поиска в каждой строке:

С флагом глобальной замены sed заменяет все вхождения шаблона поиска:

Как вы могли заметить, подстрока foo внутри строки foobar также заменена в предыдущем примере. Если это нежелательное поведение, используйте выражение границы слова ( b ) на обоих концах строки поиска. Это гарантирует, что частичные слова не совпадают.

Чтобы сделать совпадение с шаблоном нечувствительным к регистру, используйте флаг I В приведенном ниже примере мы используем флаги g и I

Если вы хотите найти и заменить строку, содержащую символ-разделитель ( / ), вам нужно будет использовать обратную косую черту ( ), чтобы избежать косой черты. Например, чтобы заменить /bin/bash на /usr/bin/zsh вы должны использовать

Более простой и понятный вариант — использовать другой символ-разделитель. Большинство людей используют вертикальную полосу ( | ) или двоеточие ( : ) , но вы можете использовать любой другой символ:

Вы также можете использовать регулярные выражения. Например, чтобы найти все трехзначные числа и заменить их строковым number вы должны использовать:

Еще одна полезная функция sed заключается в том, что вы можете использовать символ амперсанда & который соответствует сопоставленному шаблону. Персонаж можно использовать несколько раз.

Например, если вы хотите добавить фигурные скобки <> вокруг каждого трехзначного числа, введите:

И последнее, но не менее важное: всегда рекомендуется делать резервную копию при редактировании файла с помощью sed . Для этого просто укажите расширение файла резервной копии для параметра -i . Например, чтобы отредактировать file.txt и сохранить исходный файл как file.txt.bak вы должны использовать:

Чтобы убедиться, что резервная копия создана, выведите список файлов с помощью команды ls :

Рекурсивный поиск и замена

Иногда может потребоваться рекурсивный поиск в каталогах файлов, содержащих строку, и замена строки во всех файлах. Это можно сделать с помощью таких команд, как find или grep для рекурсивного поиска файлов в каталоге и передачи имен файлов в sed .

Следующая команда будет рекурсивно искать файлы в текущем рабочем каталоге и передавать имена файлов в sed .

Чтобы избежать проблем с файлами, содержащими пробелы в своих именах, используйте параметр -print0 , который указывает find напечатать имя файла, за которым следует нулевой символ, и xargs -0 вывод в sed используя xargs -0 :

Чтобы исключить каталог, используйте параметр -not -path . Например, если вы заменяете строку в локальном репозитории git, чтобы исключить все файлы, начинающиеся с точки ( . ), Используйте:

Если вы хотите искать и заменять текст только в файлах с определенным расширением, вы будете использовать:

Другой вариант — использовать команду grep для рекурсивного поиска всех файлов, содержащих шаблон поиска, а затем передать имена файлов в sed :

Выводы

Хотя это может показаться сложным и сложным, поначалу поиск и замена текста в файлах с помощью sed очень просты.

Чтобы узнать больше о sed команд, опций и флагов, посетить GNU СЭД руководство и Grymoire СЭД учебник .

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Источник

How to Find and Replace a String in File Using the sed Command in Linux

When you are working on text files you may need to find and replace a string in the file.

Sed command is mostly used to replace the text in a file.

This can be done using the sed command and awk command in Linux.

In this tutorial, we will show you how to do this using the sed command and then show about the awk command.

What is sed Command

Sed command stands for Stream Editor, It is used to perform basic text manipulation in Linux. It could perform various functions such as search, find, modify, insert or delete files.

Also, it’s performing complex regular expression pattern matching.

It can be used for the following purpose.

  • To find and replace matches with a given format.
  • To find and replace specific lines that match a given format.
  • To find and replace the entire line that matches the given format.
  • To search and replace two different patterns simultaneously.

The fifteen examples listed in this article will help you to master in the sed command.

If you want to remove a line from a file using the Sed command, go to the following article.

Note: Since this is a demonstration article, we use the sed command without the -i option, which removes lines and prints the contents of the file in the Linux terminal.

But if you want to remove lines from the source file in the real environment, use the -i option with the sed command.

Common Syntax for sed to replace a string.

First we need to understand sed syntax to do this. See details about it.

  • sed: It’s a Linux command.
  • -i: It’s one of the option for sed and what it does? By default sed print the results to the standard output. When you add this option with sed then it will edit files in place. A backup of the original file will be created when you add a suffix (For ex, -i.bak
  • s: The s is the substitute command.
  • Search_String: To search a given string or regular expression.
  • Replacement_String: The replacement string.
  • g: Global replacement flag. By default, the sed command replaces the first occurrence of the pattern in each line and it won’t replace the other occurrence in the line. But, all occurrences will be replaced when the replacement flag is provided
  • / Delimiter character.
  • Input_File: The filename that you want to perform the action.

Let us look at some examples of commonly used with sed command to search and convert text in files.

We have created the below file for demonstration purposes.

1) How to Find and Replace the “first” Event of the Pattern on a Line

The below sed command replaces the word unix with linux in the file. This only changes the first instance of the pattern on each line.

2) How to Find and Replace the “Nth” Occurrence of the Pattern on a Line

Use the /1,/2. /n flags to replace the corresponding occurrence of a pattern in a line.

The below sed command replaces the second instance of the “unix” pattern with “linux” in a line.

3) How to Search and Replace all Instances of the Pattern in a Line

The below sed command replaces all instances of the “unix” format with “Linux” on the line because “g” means a global replacement.

4) How to Find and Replace the Pattern for all Instances in a Line from the “Nth” Event

The below sed command replaces all the patterns from the “Nth” instance of a pattern in a line.

5) Search and Replace the pattern on a specific line number

You can able to replace the string on a specific line number. The below sed command replaces the pattern “unix” with “linux” only on the 3rd line.

6) How to Find and Replace Pattern in a Range of Lines

You can specify the range of line numbers to replace the string.

The below sed command replaces the “Unix” pattern with “Linux” with lines 1 through 3.

7) How to Find and Change the pattern in the Last Line

The below sed command allows you to replace the matching string only in the last line.

The below sed command replaces the “Linux” pattern with “Unix” only on the last line.

8) How to Find and Replace the Pattern with only Right Word in a Line

As you might have noticed, the substring “linuxunix” is replaced with “linuxlinux” in the 6th example. If you want to replace only the right matching word, use the word-boundary expression “\b” on both ends of the search string.

9) How to Search and Replaces the pattern with case insensitive

Everyone knows that Linux is case sensitive. To make the pattern match with case insensitive, use the I flag.

10) How to Find and Replace a String that Contains the Delimiter Character

When you search and replace for a string with the delimiter character, we need to use the backslash “\” to escape the slash.

In this example, we are going to replaces the “/bin/bash” with “/usr/bin/fish”.

The above sed command works as expected, but it looks bad. To simplify this, most of the people will use the vertical bar “|”. So, I advise you to go with it.

11) How to Find and Replaces Digits with a Given Pattern

Similarly, digits can be replaced with pattern. The below sed command replaces all digits with “6” “number” pattern.

12) How to Find and Replace only two Digit Numbers with Pattern

If you want to replace the two digit numbers with the pattern, use the sed command below.

13) How to Print only Replaced Lines with the sed Command

If you want to display only the changed lines, use the below sed command.

  • p – It prints the replaced line twice on the terminal.
  • n – It suppresses the duplicate rows generated by the “p” flag.

14) How to Run Multiple sed Commands at Once

The following sed command detect and replaces two different patterns simultaneously.

The below sed command searches for “linuxunix” and “CentOS” pattern, replacing them with “LINUXUNIX” and “RHEL8” at a time.

The following sed command search for two different patterns and replaces them with one string at a time.

The below sed command searches for “linuxunix” and “CentOS” pattern, replacing them with “Fedora30” at a time.

15) How to Find and Replace the Entire Line if the Given Pattern Matches

If the pattern matches, you can use the sed command to replace the entire line with the new line. This can be done using the “C” flag.

16) How to Search and Replace lines that Matches a Pattern

You can specify a pattern for the sed command to fit on a line. In the event of pattern matching, the sed command searches for the string to be replaced.

The below sed command first looks for lines that have the “OS” pattern, then replaces the word “Linux” with “ArchLinux”.

Источник

Читайте также:  Настройка windows 10 для майнинга amd
Оцените статью