Linux vi replace string

1. Basic replacement 

: s/vivian/sky/ replaces the first vivian of the current line with sky 

:s/vivian/sky/g replaces all vivians in the current line with sky 

:n, $s/vivian/sky/ replaces the nth line The first vivian of each line from the beginning to the last line is sky 

:n,$s/vivian/sky/g to replace the nth line from the beginning to the last line, all the vivians of each line are sky 

(n is a number, if n is ., Indicates from the current line to the last line) 

:%s/vivian/sky/ (equivalent to: g/vivian/s//sky/) Replace the first vivian of each line with sky 

:%s/vivian/sky/g (equivalent to: g/vivian/s//sky/g) Replace all vivian in each line with sky 

2. You can use # as a separator, and the / in the middle will not be used as a separator 

: s#vivian/#sky /# Replace the first vivian/ of the current line with sky/ 

:%s+/oradata/apras/+/user01/apras1+ (use + to replace / ): replace /oradata/apras/ with /user01/apras1/ 

3. Delete the text ^M 

problem description in: For line feed, it is represented by carriage return and line feed (0A0D) under windows, and it is represented by carriage return (0A) under linux. In this way, when copying files from windows to Unix, there will always be a ^M. Please write a shell or C program that filters the line breaks (0D) of windows files under Unix. 

Use the command: cat filename1 | tr -d "^V^M" > newfile; 

use the command: sed -e "s/^V^M//" filename > outputfilename 

It should be noted that in the 1 and 2 methods, ^V and ^M refer to Ctrl+V and Ctrl+M. You have to type by hand, not paste. 

Processing in vi: first use vi to open the file, then press the ESC key, then enter the command: 

:%s/^V^M// 
:%s/^M$//g 

If the above method is useless, the correct solution Yes: 

tr -d “\r” < src >dest 

tr -d “\015″ dest 

strings A>B 

4. Other usages 

can use the :s command to replace strings. Specific usages include: 

:s/str1/str2/ Replace the first occurrence of the string str1 on the line with the string str2 

:s/str1/str2/g Replace all occurrences of the string str1 on the line with the string str2 

:.,$ s/str1/str2/g replaces all occurrences of the string str1 

:1,$ s/str1/str2/g with the string str2 from the current line to the end of the text string str1 :1,$ s/str1/str2/g replaces all occurrences of the text string str1 

:g/ with the string str2 The functions of str1/s//str2/g are  the same

as above. It can be seen from the above replacement command: g is placed at the end of the command, which means that every occurrence of the search string is replaced; no g is added, which means that only the first occurrence of the search string is performed Replace; g is placed at the beginning of the command to replace all lines in the text that contain the search string.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326696947&siteId=291194637
Recommended