definition

sed is a stream editor that processes one line of content at a time

The process of text processing: ( mode space is the key )

Format: sed [-hn][-e<script>][-f<script file>][file]

  • -h : Display the help file\
  • -n : Only display the processed results of script
  • -e<script> : The script specified in the option has been used to process the input text file\
  • -f<script file>: The script file specified in the option has been used to process the input text file\

Common actions (the below 16129df00b6eee will not change the content of the source file )

  • a : add new; sed -e '4 a newline' : add a new line after line 4\
  • c : Replace; sed -e '2-5 c No 2-5 number' \
  • d : delete; sed -e '2,5 d' : delete the second and fifth lines\
  • i : insert; sed -e '2 i newline' : insert a row before the second row\
  • p : print; sed -n '/root/p' : only print the line containing root; /***/ represents the regular matching syntax script\
  • s : replace; sed -e 's#old#new#g' : replace old with new, g represents global replacement; # can be replaced with /,@ etc.\

Practical application

  • Add a new string after line 4
$ cat test
root root hello root
root
root
leo
kate
hogwart
string
leon
$ sed -e '4 a newline' test
root root hello root
root
root
leo
newline  # 新插入的行
kate
hogwart
string
leon
  • Add a new string before line 2
$ sed -e '2 i newline' test
root root hello root
newline  # 在第2行前添加
root
root
leo
kate
hogwart
string
leon
  • Global replacement
$ sed -e 's/root/hello/g' test
hello hello hello hello
hello
hello
leo
kate
hogwart
string
leon
  • Modify the source file directly; Note: The source file must be backed up in
$ sed -i 's/root/user/' test
$ cat test
user root hello root
user
user
leo
kate
hogwart
string
leon

Course practical application

  • Combine the w command to view the number of online people
w | sed '1, 2d' | awk '{print $1}' | sort | uniq -c | wc -l

机智的测试生活
88 声望478 粉丝

公号|机智的测试生活