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".