Linux finds the way to replace text content by command.

  

Linux system can use the command line to perform various operations compared with other systems, which is a prominent feature. Today Xiaobian will share with you how to use the command in the Linux system to find and replace the contents of the file.

How to use the Find and Replace command on the contents of the file:

Batch Find content contained in the heads of a file, for example:

# grep -. Rn "Find the text you are looking for" ./

2. Find and replace the contents of the file in batches.

# sed -i "s/Find text to find/replaced text/g" `grep -rl "Find text to find" ./`

sed Other usages are as follows:

1. Delete the first space of the line

sed 's/^[ ]*//g' filename

sed 's/^ *//g' filename

sed 's/^[[:space:]]*//g' filename

2. Add a new line after the line and before the line

After: sed 's/pattern/&\ /g' filename

Before the line: sed 's/pattern/\ &/g' filename

& represents pattern

3, use variable substitution (use double quotes)

sed -e "s/$var1/$var2/g" filename

4, insert before the first line Text

sed -i '1 i\\insert string ' filename

5, insert in the last line

sed -i '$ a\\insert string ' filename< Br>

6, insert before the matching line

sed -i '/pattern/i " insert string "' filename

7, insert the matching line after the

sed -i '/pattern/a &qu Ot; insert string "' filename

8, delete the line of text lines and spaces and the line of ## comment

grep -v ^# filename |  Sed /^[[:space:]]*$/d |  Sed /^$/d

find command

find -name 'filename to look for' |  Xargs perl -pi -e 's| The string being replaced | Replaced string | G'

#find replace the current directory containing strings and replace them

find -name '*.txt' |  Xargs perl -pi -e 's| Wisdom village| Northern mountains | g'

#recursive lookup replacement

find . -type f -name '*.html' |  Xargs perl -pi -e 's| Wisdom village| Northern mountains | g'

#Search directory LOG contains display

find ./-name '*log*' -type d

find ./-name '*Log*' -type d more

Of course, you can also use linux vim bulk replacement

to replace only the current line:

Example

:s/XXX/YYY /g

, if you need to replace all:

Example

:%s/XXX/YYY/g

If you need to replace the specified part You can use V to enter the visual mode, then

Example

:s/XXX/YYY/g

or you can specify the number of rows to replace the specified range:

Example

:10,31s/XXX/YYY/g

If you need to display the line number, under vim

Example

: Set nu

Cancel the display line number:

Example

:set nonu

:s/well/good/Replace the current line with the first well Good Previous12Next page Total 2 pages

Copyright © Windows knowledge All Rights Reserved