Волшебство линии команды Linux - найдите и замените

[[by]] Sukrit Dhandhania на 24-ое декабря 2008

Linux

Когда вы работаете на линии команды Linux и вы come across большой архив или большое количество архивов в вам нужно заменить некоторый текст с другими, находить и наклеивать над каждым примером текста могут быть временем бита - уничтожающ. Наилучшим образом, потревожьтесь no more. Linux имеет как раз разрешение для вас. Здесь дорога найти и заменить шнур текста в one or more архивах автоматически.

For the purpose of эта тренировка, котор мы будем использовать вызванный инструмент линии команды Linux «sed». ? » sed» будет очень мощным и разносторонним инструментом, и много может быть написано о своих возможностях. Мы используем очень лимитированный аспект «sed» здесь. Я определенно порекомендовал бы что вы читаете вверх по немного больше на «sed» если вы находите этот аспект его интересуя.

Мы идем использовать following синтаксис для того чтобы найти и заменить шнур текста в архиве:

# sed - I' s/[original_text]/] [new_text/' filename.txt

Мнение вы имеете вызванный архив «database.txt» с многочисленнIp примерами ip address вашего сервера базы данных в ем. Вам как раз переключали к новому серверу базы данных и нужно уточнить его с ip address нового сервера. Старым ip address будет 192.168.1.16 и new one будет 192.168.1.22. Здесь будет как вы идете о ем:

# кот database.txt
LOCAL_DATABASE = 192.168.1.16
LOCAL_DIR = /home/calvin/
PROD_DB = 192.168.1.16

#?sed - I' s/192.168.1.16/192.168.1.22 /g'? database.txt
# cна database.txt
LOCAL_DATABASE = 192.168.1.22
LOCAL_DIR = /home/calvin/
PROD_DB = 192.168.1.22

Теперь раскройте архив «database.inc» и проверите для того чтобы увидеть если новое ip address осуществляло ваше старое одного. Здесь breakup вышеуказанной команды. Во первых вы вызываете «sed» команда. После этого вы проходите им параметр «- s» стоит для «in place of». Теперь мы используем немного регулярно выражений, общ известно как «regex»? для следующего бита. «S» в стойках закавыченного шнура для «замены», и «g» на стойках конца для «глобального». Между ими они приводят к в «глобальном замещении шнура текста, котор вы устанавливаете между ими.

Вы можете опционно прыгнуть «g» на конце. Это намеревается что замещение не будет глобально, которое практически переводит к замещению только первого примера шнура в линии. Так если вы имели линию с множественными примерами текста, котор вы пытаетесь заменить, здесь будет случится

# cat database.txt
LOCAL_DATABASE = 192.168.1.16
LOCAL_DIR = /home/calvin/
PROD_DB = 192.168.1.16, 192.168.1.16

#?sed -i ’s/192.168.1.16/192.168.1.22/’?database.txt
# cat database.txt
LOCAL_DATABASE = 192.168.1.22
LOCAL_DIR = /home/calvin/
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/’ {} \

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. “find .?maxdepth 1″ tell the computer to look in the current directory and go no deeper than the current directory. The ‘-name??”*.txt”‘ part tells find to only list files with the extension of “.txt”. Then the “-type f” section specifies that “find” should only pick exactly matching files. 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/’ {} \”.

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.

Related Posts:
  • Some useful Linux bash tricks
  • Running process in the background with Nohup
  • Get started using the Vim text editor
  • How to download files from the Linux command line
  • How to set the date on your Linux machine
  • Get Simple Help tutorials just like this one in your email inbox every day - for free! Just enter your email address below:

    You can always opt out of this email subscription at any time.


    Bookmark and Share

    { 3 comments… read them below or add one }

    1 marco 12.29.08 at 11:36 pm

    > Then you pass it the parameter ?-s? which stands for ?in place of?.
    I think it must be ?-i?

    2 myhnet 12.31.08 at 9:03 pm

    Now open the file ?database.inc? and check to see if the new IP address has taken place of your old one.

    database.inc here I think it should be database.txt

    3 Faustino 01.19.09 at 3:56 pm

    Eso es muy facil….
    pero por ejemplo como harias lo siguiente
    tienes una ruta windows en un codigo y quieres pasarla a ruta de tipo linux
    la cadena que buscas es C:\ejemplos\archivos\aqui
    Cambiarla a /ejemplos/archivos/aqui

    para un grupo de archivos que se encuentran en la misma carpeta…

    Leave a Comment

    You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>