Linux under VI replacement character Command example

Source: Internet
Author: User
Tags linux

In Linux development, often involves processing the characters in the file, in which the replacement of characters is also very frequent.

This paper takes a practical document as an example, introduces in detail the common VI substitution character commands under Linux, and provides a reference for the related development work.

The file being manipulated in this article is TestFile.txt, which reads as follows:

Zhou@linux:~/zhouzx/test> Cat TestFile.txt

12345678907890

Abcdabcdefghij

12345^&* () ()

98765432103210

Abcdabcdefghij123123

First into the vi editing mode, as follows:

Zhou@linux:~/zhouzx/test> VI TestFile.txt

In turn, execute the following substitution commands (note: Each command starts with a colon ":"), where the replacement part is marked with a red font.

1): N, $s/str1/str2/

Replaces the first str1 with the str2 for each row in the last line of the nth row.

For example, execute in the VI edit mode of the TestFile.txt file:

: 2, $s/123/321/

The contents of the file become:

12345678907890

Abcdabcdefghij

32145^&* () ()

98765432103210

Abcdabcdefghij321123

Visible, only the third and fifth lines of the first "123" into "321". The first line of "123" was not replaced because the command was executed from the second line.

2): N, $s/str1/str2/g

Replace the nth row with all str1 in each row of the last line str2.

Immediately following the previous command:

: 2, $s/3210/1234/g

The contents of the file become:

12345678907890

Abcdabcdefghij

32145^&* () ()

98765412341234

Abcdabcdefghij321123

Visible, all of the "3210" from the second line became "1234".

3):%s/str1/str2/

Replace the first str1 of each row with str2.

Immediately following the previous command:

:%s/123/321/

The contents of the file become:

32145678907890

Abcdabcdefghij

32145^&* () ()

98765432141234

abcdabcdefghij321321

Visible, each row of the first "123" has become "321".

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.