先提供一个文本,主要以hello字符串为主,包含大写类型,一行多个hello等情况。
➜ linux_commands cat hello.txt
hello world
hello boys
she is saying hello
hello hello
HELLO everyone
- sed (-l) 's/old_text/new_text/(g)' [file]: 输出文件[file]中每行第1个old_text替换成new_text的结果,最后加g表示替换所有匹配。
➜ linux_commands sed -l 's/hello/hi/' hello.txt
hi world
hi boys
she is saying hi
hi hello
HELLO everyone
➜ linux_commands sed 's/hello/hi/' hello.txt
hi world
hi boys
she is saying hi
hi hello
HELLO everyone
➜ linux_commands sed 's/hello/hi/g' hello.txt
hi world
hi boys
she is saying hi
hi hi
HELLO everyone
- sed -i "" 's/old_text/new_text/' [file]: 替换字符串并写入文件
➜ linux_commands sed -i "" 's/hello/hi/' hello.txt
➜ linux_commands cat hello.txt
hi world
hi boys
she is saying hi
hi hello -->由于未加g参数,所以第二个hello未替换
HELLO everyone
- sed -e 's/old_text1/new_text1/' -e 's/old_text2/new_text2/' [file]: 对文件[file]内容将old_text1替换成new_text1或将old_text2替换成new_text2
➜ linux_commands sed -e 's/boys/men/' -e 's/she/he/' hello.txt
hi world
hi men
he is saying hi
hi hello
HELLO everyone
- sed -n 'line_num,/^$/p' [file]: 打印从行号line_num到下一个空行之间的内容,/p表示打印
➜ linux_commands sed -n '1,/^$/p' hello.txt
hi world
hi boys
➜ linux_commands head -4 hello.txt
hi world
hi boys
she is saying hi