Sed foundation in Linux

sed is a stream editor, it is very important text processing tool that can perfectly fit the regular expression to use, extraordinary. Handling, storing the row currently being processed in a temporary buffer, called a "model space" (pattern space), followed by treatment with the contents of the buffer sed command, the processing is completed, the contents of the buffer sent to the screen. Then the next line, which is repeated until the end of the file. File contents not changed, unless you use redirection to store the output. Sed is mainly used to automatically edit one or more documents; simplify repeated operation of the document; write conversion procedures.

sed commands commonly used parameters

Common Commands

Function command Explanation
1,n We need to operate the line, the first line to the N-th row
s search search and replace, use this command up to
a Add append
i insert insert
c replace
d Delete Row
p print

There are two most important parameter
-n use the quiet (silent) mode. Sed in general usage, all data from STDIN generally will be listed to the terminal. However, if after adding -n parameter, only through the line sed special treatment (or action) will be listed.
-i replace the original file directly, without -i original file is not modified, but the output of the memory or place.

Use sed commonly used commands

cat test.txt
111
222
333
444
555
666
777
打印第三行至第五行
sed -n '3,5p' test.txt
333
444
555
删除第三至第五行
sed  '3,5d' test.txt
111
222
666
777
删除第三至第五行并修改原文件
sed -i '3,5d' test.txt
cat test.txt
111
222
666
777
第二行之前添加qqq
sed '2i qqq' test.txt
111
qqq
222
333
444
555
666
777
第二行之后添加qqq
sed '2a qqq' test.txt
111
222
qqq
333
444
555
666
777
第二行替换为qqq
sed '2c qqq' test.txt
111
qqq
333
444
555
666
777

sed s most important command, Find and Replace

sed "s / search / replace / g" g represents a row Replace All, the replacement of only a default line

cat test.txt
111
222
111
444
555
sed "s/1/php/" test.txt
php11
222
php11
444
555
sed "s/1/php/g" test.txt
phpphpphp
222
phpphpphp
444
555

With regular similar. ^ Represents the beginning of each line, $ indicates the end of each line. Regular match is to follow the specification.

每一行开始加//
sed "s/^/\/\//g" test.txt
//111
//222
//111
//444
//555
每一行行尾加;
sed "s/$/;/g" test.txt
111;
222;
111;
444;
555;

Replace the condition of a single character

替换每一行的第二匹配字符1,替换成+
sed "s/1/+/2" test.txt
1+1
222
1+1
444
555

Replaced with a plurality of matching; separated

把2替换成+,把4替换成-
sed "s/2/+/g;s/4/-/g" test.txt
111
+++
111
---
555

Subset parentheses, using \ 1 \ 2 \ n which results in the alternative

cat test.txt
1hello1
222
111
444
555
sed "s/1\(.*\)1/wo\1/g" test.txt
wohello
222
wo1
444
555

Commonly used project file to replace

把当前项目中所有文件中的111替换成helloworld
sed -i "s/111/helloworld/g" `grep -rl . *`

Guess you like

Origin www.cnblogs.com/feixiangmanon/p/12043757.html