[Sed] Linux sed replaces strings in batches

Source: Internet
Author: User

Original article in: http://bbs.linuxtone.org/thread-1731-1-1.html

For example, to change the zhangsan in all the files under the directory/modules to Lisi, do the following:

Sed-I "s/zhangsan/Lisi/g" 'grep zhangsan-RL/Les'

Explanations:

-I indicates inplace edit, modifying files in place
-R indicates searching for subdirectories
-L indicates the output file name.

This command combination is very powerful, pay attention to backup files.


(1) Sed 'y/1234567890/abcdefghij/'test_sed
Sed 'y/1234567890/abcdefghij/'filename
Abcdefghij
Bcdefghija
Cdefghijab
Defghijabc
Note that the conversion relationship is converted according to the positions of the two lists.
The content of test_sed is:
1234567890
2345678901
3456789012
4567890123

(2) Replace all matches in each line
Sed's/01/AB/G' test_sed
1234567890
23456789ab
3456789ab2
456789ab23
Note: The first line 0, 1 is not replaced with a, B

Delete: D command

  • $ Sed '2d 'example ----- Delete the second line of the example file.
  • $ Sed '2, $ d' example ----- delete all rows from the second row to the end of the example file.
  • $ Sed '$ d' example ----- Delete the last row of the example file.
  • $ Sed '/test/'d example ----- delete all rows containing test in the example file.

Replace: s command

  • $ SED's/test/mytest/G' example ----- replace test with mytest in the entire row. If no G tag exists, only the first matched test in each row is replaced with mytest.
  • $ Sed-n's/^ test/mytest/P 'example ----- (-N) option and the P Flag are used together to print only the replaced rows. That is to say, if the test at the beginning of a row is replaced with mytest, print it.
  • $ SED's/^ 192.168.0.1/& localhost/'example ----- & symbol indicates replacing the part found in the string. All rows starting with 192.168.0.1 are replaced with their own localhost and changed to 192.168.0.1localhost.
  • $ Sed-n's/\ (love \) Able/\ 1RS/P 'example ----- love is marked as 1, and all loveable will be replaced with lovers, the replaced line is printed out.
  • $ SED's #10 #100 # g'example ----- whatever the character, followed by the S command is considered as a new separator. Therefore, "#" is a separator here, replaces the default "/" separator. Replace all 10 with 100.

Range of selected rows: comma

  • $ Sed-n'/test/,/check/P' example ----- all rows within the range specified by the template test and check are printed.
  • $ Sed-n' 5,/^ test/P' example ----- print all rows starting from the fifth line to the first line that contains the beginning of test.
  • $ Sed '/test/,/check/S/$/SED test/' example ----- for the rows between the template test and west, the end of each row is replaced by the string sed test.

Multi-Point Editing: e command

  • $ Sed-e '1, 5d '-E's/test/check/'example ----- (-e) options allow multiple commands to be executed in the same line. As shown in the example, the First Command deletes lines 1 to 5, and the second command replaces test with check. The command execution sequence has an impact on the result. If both commands are replacement commands, the first replacement command will affect the result of the second replacement command.
  • $ Sed -- Expression ='s/test/check/'-- Expression ='/love/d' example ----- a better command than-E is -- expression. It can assign values to SED expressions.

Read from file: R command

  • $ Sed '/test/R file' example ----- the content in file is read and displayed after the row matching test. If multiple rows match, the file content is displayed under all matched rows.

Write File: W command

  • $ Sed-n'/test/W file' example ----- all rows containing test in example are written to file.

APPEND Command: command

  • $ Sed '/^ test/A \ ---> This Is A example 'example <----- 'this is a example' is appended to the end of the row starting with test, sed requires that command a be followed by a backslash.

Insert: I command $ sed '/test/I \\
New Line
------------------------- 'Example
If test is matched, the text following the backslash is inserted before the matching row.
Next: N command

  • $ Sed '/test/{n; S/AA/BB/;}' example ----- if test is matched, move it to the next row of the matched row and replace AA of this row, change to BB, print the row, and continue.

Deformation: y command

  • $ Sed '1, 10y/ABCDE/'example ----- converts all ABCDE in line 1-10 to uppercase. Note that this command is not applicable to the regular expression metacharacters.

Exit: Q command

  • $ Sed '10q' example ----- exit sed after printing the 10th rows.

Maintain and obtain: H and G commands

  • $ Sed-e '/test/H'-e' $ gexample ----- when sed processes files, each row is saved in a temporary buffer called a mode space, all processed rows are printed on the screen unless the row is deleted or the output is canceled. The mode space is cleared, and a new row is saved for processing. In this example, the row Matching Test is found and saved to the mode space. The H Command copies the row and saves it to a special buffer zone called keep cache. The second statement means that when the last line is reached, the G command extracts the row that maintains the buffer and places it back in the mode space, and append it to the end of the row that already exists in the mode space. In this example, It is appended to the last row. Simply put, any row containing test is copied and appended to the end of the file.

Persistence and interchange: H and X commands

  • $ Sed-e '/test/H'-e'/check/X' example ----- swap mode space and keep the buffer content. That is, to swap the rows containing test and check.

7. Script

Sed script is a list of SED commands. When SED is started, the file name of the script is guided by the-F option. Sed is very picky about the commands entered in the script. There cannot be any blank or text at the end of the command. If there are multiple commands in one line, separate them with semicolons. Comments rows starting with # And cannot span rows.

8. Tips

  • Use double quotation marks when referencing shell variables in the SED command line, instead of the common single quotation marks. The following is a script to delete the zone segment in the named. conf file based on the content of the name variable:
    Name = 'zone \ "localhost "'
    Sed "/$ name/,/};/D" named. conf

Sed-I "s/oldstring/newstring/g" 'grep oldstring-rl yourdir'

For example, replace www.itbbs.cn with chinafar.com in all files under/home.

Sed-I "s/www.itbbs.cn/chinafar.com/g" 'grep www.itbbs.cn-RL/home'

2. the following command:
Perl-pi-E's | ABCD | Linux | g'' find./-type F'
Execute a replacement command by calling Perl, and replace the ABCD in all files found by the find command with

Find./-type F
This command displays all files in the current directory

The above "s | ABCD | Linux | G" is the script to be executed by Perl, that is, replacing all ABCD with Linux
If you do not write the last g, "s | ABCD | Linux |" will only replace the ABCD starting with each line.

When the edit command (refer to [section2.2]) is executed on the command column, option-e must be added before it. The command format is as follows:

Sed-e' edit command 1'-e' edit command 2'... file File

All the edit commands are immediately following option-E and placed between two "'" special characters. In addition, the command is edited

Left and right.

Generally, when there are few commands to edit, users usually execute them directly on the command.

For example, delete 1 to 10 lines of data in Yel. dat and change the "yellow" string in the remaining text to the "black" string. In this case, you can run the edit command directly on the command. The command is as follows:

Sed-e '1, 10d '-E's/yellow/Black/G' Yel. dat

In the command, edit the command '1, 10d '(solution [5]) and delete lines 1 to 10; edit Command's/yellow/Black/G' (solution [6]),

Replace the "yellow" string (substuite) with the "black" string.

2.2sed edit command

The format of the SED edit command is as follows:

[Address1 [, address2] function [argument]

The address parameters address1 and address2 are the number of rows or the regularexpression string, indicating the row of the data to be edited. The function parameter

The number function [argument] is the SED internal function, which indicates the edited action.

The following two sections detail the representation of the address parameter and the function parameters available for selection.

2.2.1 representation of address parameters

In fact, the address Parameter Representation is only the row of the data to be edited, and they are represented by the number of lines or strings. The following are examples:

(The commands take function parameter D (refer to [section4.2]) as an example ):

If you delete the first row of data in the archive, the command is 10 days.

When you delete a row containing a "man" string, the command is/man/d.

If you delete rows from the first row to the second row, the command is 10th D.

Delete the data lines from the first row in the archive to the data line containing the "man" string. The command is 10,/man/d.

Next, let's take the content of the address parameter and its number as two points to fully describe the representation of the address parameter in the instruction (also take function parameter D as an example ).

Address parameter content:

Decimal number: This number indicates the number of rows. When the command is executed, the edit action indicated by the function parameter is executed for the data that matches the number of rows. For example,

If you delete the first row of data in the data file, the command is 15D (refer to [section4.2]). And so on. For example, if you delete Row M in a data file

Command is MD.

The address is regularexpression (refer to [appendix A]):

When the data row contains strings that conform to the regularexpression, the edit action indicated by the function parameter is executed. In addition

"/" Must be added before regularexpression "/". For example, if the command is/T. * t/d, all data lines containing two "T" letters are deleted. Where ,"."

"*" Indicates that the first character can be any number of times. They are combined with ". *" to indicate any string between two "T" letters.

Number of address parameters: In the command, if there is no address parameter, it indicates that all data rows execute the edit action indicated by the function parameter; if there is only one address

When the parameter is set, only the data row that matches the address is edited. When there are two address parameters, such as address1 and address2, the parameter is executed for the data area.

Edit. address1 indicates the start row and address2 indicates the end row. The following examples are provided to describe the above content.

For example, the command is

D

It indicates deleting all data rows in the file.

For example, the command is

5D

It indicates deleting the fifth row of data in the file.

For example, the command is

1,/Apple/d

It indicates that the data area is deleted, from the first row in the file to the row containing the "apple" string.

For example, the command is

/Apple/,/orange/d

It indicates the deletion of the data area, from the file containing the "apple" string to the data line containing the "orange" String

2.2.2 function parameters

The following table describes the functions of all sed function parameters (refer to [Chapter4.

Function Parameters

: Label creates a location for mutual reference of commands in scriptfile.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.