Skip to content Перейти до змісту


Linux command line magic – find and replace Linux Command Line магія - знайти і замінити

Linux

When you are working on the Linux command line and you come across a large file or a large number of files in which you need to replace a certain text with another, finding and pasting over each instance of the text can be a bit time consuming. Коли ви працюєте в командному рядку Linux, і ви зустрінетесь з великим файлом або великою кількістю файлів, в яких необхідно замінити слово або текст з одним, знаходити і вставляти над кожним примірником тексту може бути довготривалою розрядні час. Well, worry no more. Ну, турбуватися не більше. Linux has just the solution for you. Linux має саме для вас рішення. Here's a way to find and replace a string of text in one or more files automatically. Ось спосіб, щоб знайти і замінити рядок тексту в одному або декількох файлах автоматично.

For the purpose of this exercise we will use a Linux command line tool called “sed”. Для цієї вправи ми будемо використовувати лінію команди Linux інструмент під назвою "SED".  ”sed” is a very powerful and versatile tool, and a lot can be written about its capabilities. "SED" є дуже потужним і універсальним інструментом, і багато чого може бути написано про його можливості. We are using a very limited aspect of “sed” here. Ми використовуємо дуже обмеженому аспекті "SED" тут. I would definitely recommend that you read up a little more on “sed” if you find this aspect of it interesting. Я безумовно рекомендую Вам прочитати трохи більше про "SED" Якщо ви знайдете цей аспект його цікавим.

We are going to use the following syntax to find and replace a string of text in a file: Ми будемо використовувати наступний синтаксис, щоб знайти і замінити рядок тексту у файлі:

# sed -i 's/[orginal_text]/[new_text]/' filename.txt # СЕД-I 'S / [orginal_text] / [new_text] /' filename.txt

Say you have a file called “database.txt” with numerous instances of the IP address of your database server in it. Скажімо, у вас є файл з назвою "database.txt" з численними випадками IP адреса вашого сервера бази даних в ній. You have just switched to a new database server and need to update it with the new server's IP address. Ви тільки що перейшли на новий сервер бази даних і необхідність оновлення його IP-адресу нового сервера. The old IP address is 192.168.1.16 and the new one is 192.168.1.22. Стара адреса є IP 192.168.1.16 і новим є 192.168.1.22. Here's how you go about it: От як ви йдете про нього:

# cat database.txt # CAT database.txt
LOCAL_DATABASE = 192.168.1.16 LOCAL_DATABASE = 192.168.1.16
LOCAL_DIR = /home/calvin/ Local_dir = / Home / Calvin /
PROD_DB = 192.168.1.16 PROD_DB = 192.168.1.16

# sed -i 's/192.168.1.16/192.168.1.22/g' database.txt # СЕД-database.txt s/192.168.1.16/192.168.1.22/g я '
# c at database.txt # C на database.txt
LOCAL_DATABASE = 192.168.1.22 LOCAL_DATABASE = 192.168.1.22
LOCAL_DIR = /home/calvin/ Local_dir = / Home / Calvin /
PROD_DB = 192.168.1.22 PROD_DB = 192.168.1.22

Now open the file “database.inc” and check to see if the new IP address has taken place of your old one. Тепер відкрийте файл "database.inc" і перевірити, щоб переконатися, що новий IP адреса походить від старого. Here's the breakup of the above command. Ось розпаду вище команди. First you call the “sed” command. Перший виклик команди "Sed". Then you pass it the parameter “-s” which stands for “in place of”. Потім ви передаєте його параметром "-S", що означає "на місці". Now we use a little bit of regular expressions, commonly known as “regex”  for the next bit. Тепер ми використовуємо трохи регулярних виразів, широко відомий як "регулярний вираз" для наступного бита. The “s” in the quoted string stands for “substitute”, and the “g” at the end stands for “global”. "S" в лапки означає "замінити словами" та "G" наприкінці означає "глобальне". Between them they result in a “global substitution of the the string of text you place in between them. Між ними вони призводять до "глобальної заміна рядків тексту, місце між ними.

You can optionally skip the “g” at the end. Необов'язково ви можете пропустити "G" на кінці. This means that the substitution will not be global, which practically translates to the substitution of only the first instance of the string in a line. Це означає, що заміна не буде носити глобальний характер, що практично переводить до заміни тільки перший примірник рядок в рядок. So if you had a line with multiple instances of the text you are trying to replace, here's what will happen Так що якщо у вас є рядок з кількома примірниками тексту, який Ви намагаєтеся замінити, ось що трапиться

# cat database.txt # CAT database.txt
LOCAL_DATABASE = 192.168.1.16 LOCAL_DATABASE = 192.168.1.16
LOCAL_DIR = /home/calvin/ Local_dir = / Home / Calvin /
PROD_DB = 192.168.1.16, 192.168.1.16 PROD_DB = 192.168.1.16, 192.168.1.16

# sed -i 's/192.168.1.16/192.168.1.22/' database.txt # СЕД-s/192.168.1.16/192.168.1.22 Я database.txt / '
# cat database.txt # CAT database.txt
LOCAL_DATABASE = 192.168.1.22 LOCAL_DATABASE = 192.168.1.22
LOCAL_DIR = /home/calvin/ Local_dir = / Home / Calvin /
PROD_DB = 192.168.1.22, 192.168.1.16 PROD_DB = 192.168.1.22, 192.168.1.16

Here comes the real magic. А от реальна магія. Now, say you want to change a string of text not just in a single file, but in the entire directory you are in. There are a number of text files in which you need to find and replace the “wine” with “champagne”. Тепер, скажімо, ви хочете змінити рядок тексту, а не тільки в одному файлі, але й у всьому каталозі Ви відвідуєте Є кілька текстових файлів, в яких вам потрібно буде знайти і замінити "вина" на "шампанське" .

# find . # Знайти. -maxdepth 1 -name “*.txt” -type f -exec sed -i 's/wine/champagne/' {} \ MaxDepth-1-назву "*. TXT" типу F-Exec Sed-I 'S / вино / шампанське /' () \

We use the find command to get a list of all the text files in the current directory. Ми використовуємо знайти команду, щоб отримати список всіх текстових файлів у поточному каталозі. That's the “find . Ось "знайти. -maxdepth 1 -name “*.txt” -type f” part. MaxDepth-1-назву "*. TXT типу" F "частини. “find . maxdepth 1″ tell the computer to look in the current directory and go no deeper than the current directory. "Знайти. MaxDepth 1" Скажи комп'ютеру шукати в поточному каталозі і не йдуть глибше, ніж у поточному каталозі. The '-name  ”*.txt”' part tells find to only list files with the extension of “.txt”. 'Ім'я "*. TXT" "частина розповідає знайти в списку лише ті файли з розширенням". Txt ". Then the “-type f” section specifies that “find” should only pick exactly matching files. Тоді типу "F" вказує, що розділ "Пошук" слід тільки вибрати точно відповідних файлів. Finally the “-exec” part tells “find” to execute the command that follows, which, in this case, is the “sed” command to replace the text – “sed -i 's/wine/champagne/' {} \”. Нарешті, "-Exec" частина оповідає "Пошук", щоб виконати команду, яку слід, що в даному випадку, команда "Sed" замінити текст - "SED-I 'S / вино / шампанське /' () \ ".

I realize that the above command seems complicated. Я розумію, що здається складним вище команди. However, once you use it a little bit you will realize that it is probably worth noting it down and using it. Однак, якщо ви використовуєте його трохи ви зрозумієте, що це, ймовірно, варто відзначити його і його використання. Now try changing a string of text in multiple levels of directories. Тепер спробуйте змінити рядок тексту на декількох рівнях каталогів.

Posted in Опубліковано в Linux Linux . .

Related Posts: Схожі повідомлення:

How to resolve the '/bin/rm: Argument list too long' error Як дозволити '/ BIN / RM: список аргументів занадто довгий' Error
How to post to Twitter from the Linux command line Як розмістити на Twitter з командного рядка Linux
How to find your public IP address with the Linux command line Як знайти свій громадський адреса IP командний рядок Linux
How to enable the root user account in Ubuntu Linux Як включити обліковий запис користувача root в Ubuntu Linux
Bash one liner – how to compress, move, and extract a directory Баш Один балон - як стиснути, переміщати і екстракт каталозі

3 Responses 3 Відповіді

Stay in touch with the conversation, subscribe to the Залишайтеся на зв'язку при розмові, підпишіться на RSS feed for comments on this post RSS-канал для коментарів на цю посаду . .

  1. marco says Марко говорить

    > Then you pass it the parameter “-s” which stands for “in place of”. > Потім ви передаєте його параметром "-S", що означає "на місці".
    I think it must be “-i” Я думаю, що це має бути "-I"

  2. myhnet myhnet says говорить

    Now open the file “database.inc” and check to see if the new IP address has taken place of your old one. Тепер відкрийте файл "database.inc" і перевірити, щоб переконатися, що новий IP адреса походить від старого.

    database.inc here I think it should be database.txt database.inc тут я думаю, що це має бути database.txt

  3. Faustino says Фаустіни говорить

    Eso es muy facil…. Eso Es Muy Фран ....
    pero por ejemplo como harias lo siguiente Перу автора Ejemplo корисне harias Lo Siguiente
    tienes una ruta windows en un codigo y quieres pasarla a ruta de tipo linux Tienes Una рута Windows EN ООН у CODIGO Quieres pasarla рут де Tipo Linux
    la cadena que buscas es C:\ejemplos\archivos\aqui Que La Cadena Buscas ES C: \ Приклади \ Archivos \ Aqui
    Cambiarla a /ejemplos/archivos/aqui Cambiarla / Приклади / Archivos / Aqui

    para un grupo de archivos que se encuentran en la misma carpeta… пункт ООН Grupo де Archivos Que SE encuentran En La Misma папка ...



Some HTML is OK Деякі HTML нормально

or, reply to this post via чи відповідь на цей пост через trackback Архів . .