Skip to content Gå til innhold


Linux command line magic – find and replace Linux kommandolinje magi - finn og erstatt

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. Når du arbeider på Linux kommandolinje, og du kommer over en stor fil eller et stort antall filer som du trenger for å erstatte en bestemt tekst med en annen, finne og lime over hver forekomst av teksten kan være litt tidkrevende. Well, worry no more. Vel, bekymre deg lenger. Linux has just the solution for you. Linux har nettopp løsningen for deg. Here's a way to find and replace a string of text in one or more files automatically. Her er en måte å finne og erstatte en tekststreng i en eller flere filer automatisk.

For the purpose of this exercise we will use a Linux command line tool called “sed”. For hensikten med denne øvelsen vil vi bruke en Linux kommandolinje verktøy kalt "sed".  ”sed” is a very powerful and versatile tool, and a lot can be written about its capabilities. "Sed" er en meget kraftig og allsidig verktøy, og mye kan bli skrevet om sine evner. We are using a very limited aspect of “sed” here. Vi bruker en svært begrenset del av "sed" her. I would definitely recommend that you read up a little more on “sed” if you find this aspect of it interesting. Jeg vil absolutt anbefale at du leser deg litt mer på "sed" hvis du finner dette aspektet av det interessant.

We are going to use the following syntax to find and replace a string of text in a file: Vi kommer til å bruke følgende syntaks til å finne og erstatte en tekststreng i en fil:

# sed -i 's/[orginal_text]/[new_text]/' filename.txt # Sed-i 's / [orginal_text] / [ny_tekst] /' filnavn.txt

Say you have a file called “database.txt” with numerous instances of the IP address of your database server in it. Si du har en fil som heter "database.txt" med en rekke forekomster av IP-adressen til database-serveren i den. You have just switched to a new database server and need to update it with the new server's IP address. Du har nettopp byttet til en ny database server og trenger å oppdatere den med nye serverens IP-adresse. The old IP address is 192.168.1.16 and the new one is 192.168.1.22. Den gamle IP-adressen er 192.168.1.16, og den nye er 192.168.1.22. Here's how you go about it: Her er hvordan du går om det:

# 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 # Sed-i 's/192.168.1.16/192.168.1.22/g' database.txt
# c at database.txt # C på 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. Nå åpner filen "database.inc" og sjekk for å se om den nye IP-adressen har funnet sted av din gamle. Here's the breakup of the above command. Her er oppdelingen av over kommandoen. First you call the “sed” command. Først kaller "sed" kommandoen. Then you pass it the parameter “-s” which stands for “in place of”. Så du passerer den parameteren "-s" som står for "i stedet for". Now we use a little bit of regular expressions, commonly known as “regex”  for the next bit. Nå bruker vi litt av regulære uttrykk, vanligvis kjent som "regex" på neste bit. The “s” in the quoted string stands for “substitute”, and the “g” at the end stands for “global”. Den "s" i den oppgitte strengen står for "erstatning", og "g" på slutten står for "global". Between them they result in a “global substitution of the the string of text you place in between them. Mellom dem føre de i en "global substitusjon av den tekststreng du plasserer i mellom dem.

You can optionally skip the “g” at the end. Du kan eventuelt hoppe over "g" på slutten. 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. Dette betyr at substitusjonsbehandling ikke vil være globalt, noe som nærmest kan oversettes til substitusjon av bare den første forekomsten av strengen på en linje. So if you had a line with multiple instances of the text you are trying to replace, here's what will happen Så hvis du hadde en tråd med flere forekomster av teksten du prøver å erstatte, her er hva som vil skje

# 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 # Sed-i '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. Her kommer den virkelige magien. 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”. Nå, si at du ønsker å endre en tekststreng ikke bare i en enkelt fil, men i hele katalogen du er i. Det finnes en rekke tekstfiler som du trenger for å finne og erstatte "vin" med "champagne" .

# find . # Find. -maxdepth 1 -name “*.txt” -type f -exec sed -i 's/wine/champagne/' {} \ -maxdepth 1-name "*. txt"-type f-exec sed-i 's / vin / champagne /' () \

We use the find command to get a list of all the text files in the current directory. Vi bruker å finne kommandoen for å få en liste over alle tekstfiler i den gjeldende katalogen. That's the “find . Det er "å finne. -maxdepth 1 -name “*.txt” -type f” part. -maxdepth 1-name "*. txt"-type f "del. “find . maxdepth 1″ tell the computer to look in the current directory and go no deeper than the current directory. "Find. Maxdepth 1" fortelle datamaskinen til å se i den gjeldende katalogen, og går ikke dypere enn den gjeldende katalogen. The '-name  ”*.txt”' part tells find to only list files with the extension of “.txt”. The '-name "*. txt"' del forteller finner å bare vise filer med filtypen ". Txt». Then the “-type f” section specifies that “find” should only pick exactly matching files. Da "-type f delen presiserer at" Finn "skulle bare plukke nøyaktig samsvarende filer. 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/' {} \”. Endelig "-exec" delen forteller "finne" for å utføre kommandoen som følger, som i dette tilfellet er "sed-kommandoen til å erstatte teksten -" sed-i 's / vin / champagne /' () \ ".

I realize that the above command seems complicated. Jeg innser at det over kommandoen virker komplisert. However, once you use it a little bit you will realize that it is probably worth noting it down and using it. Men når du bruker den litt vil du innse at det er nok verdt å merke det ned og bruke den. Now try changing a string of text in multiple levels of directories. Nå kan du prøve å endre en tekststreng i flere nivåer av kataloger.

Posted in Posted in Linux Linux . .

Related Posts: Relaterte innlegg:

How to resolve the '/bin/rm: Argument list too long' error Hvordan løse '/ bin / rm: Argumentet listen er for lang "-feil
How to post to Twitter from the Linux command line Hvordan legge til Twitter fra Linux kommandolinjen
How to find your public IP address with the Linux command line Hvordan finne den offentlige IP-adressen med Linux kommandolinjen
How to enable the root user account in Ubuntu Linux Slik aktiverer root brukerkonto i Ubuntu Linux
Bash one liner – how to compress, move, and extract a directory Bash en liner - hvor å komprimere, flytte og pakke ut en katalog

3 Responses 3 Svar

Stay in touch with the conversation, subscribe to the Hold kontakten med samtalen, abonnere på RSS feed for comments on this post RSS feed for kommentarer til dette innlegget . .

  1. marco says marco sier

    > Then you pass it the parameter “-s” which stands for “in place of”. > Så du passerer den parameteren "-s" som står for "i stedet for".
    I think it must be “-i” Jeg tror det må være "-I"

  2. myhnet myhnet says sier

    Now open the file “database.inc” and check to see if the new IP address has taken place of your old one. Nå åpner filen "database.inc" og sjekk for å se om den nye IP-adressen har funnet sted av din gamle.

    database.inc here I think it should be database.txt database.inc her tror jeg det skal være database.txt

  3. Faustino says Faustino sier

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

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



Some HTML is OK Some HTML is OK

or, reply to this post via eller svare på dette innlegget via trackback styrekule . .