Linux常用基本命令:三剑客命令之-sed
sed是一个很强大的文件处理工具,主要是以行为单位进行处理,可以将数据行进行替换、删除、新增、选取等特定工作
格式:sed [option] [command] [file]
常用命令:
a ∶新增
c ∶取代
d ∶删除
i ∶插入
p ∶列印
s ∶取代
选项:
-i∶直接修改读取的档案内容,而不是由萤幕输出。
-n∶使用安静(silent)模式。在一般 sed 的用法中,所有来自 STDIN的资料一般都会被列出到萤幕上。但如果加上 -n 参数后,则只有经过sed 特殊处理的那一行(或者动作)才会被列出来。
1,sed ‘1d’ ghostwu.com d代表删除 d前面的数字代表删除第一行,该命令不会修改文件本身
[email protected]:~/linux/sed sed ‘1d’ ghostwu.txt
how are you
hod old are you
and you
fine thank you
come with me!!!
[email protected]:~/linux/sed代表最后一行
[email protected]:~/linux/sed sed '$d’ ghostwu.txt
this is ghostwu
how are you
hod old are you
and you
fine thank you
复制代码
3,删除第一行到第二行
[email protected]:~/linux/sed sed ‘1,2d’ ghostwu.txt
hod old are you
and you
fine thank you
come with me!!!
4,删除第二行到最后一行
[email protected]:~/linux/sedd’ ghostwu.txt
this is ghostwu
5,查找包含’you’的行, /you/ 这是正则表达式, p是打印,要跟n结合起来用
[email protected]:~/linux/sed sed -n ‘/you/p’ ghostwu.txt
how are you
hod old are you
and you
fine thank you
6,匹配$符号结尾的行
$符号在正则表达式表示行尾,所以要用\ 转义
[email protected]:~/linux/sed
7,在第一行后面,增加一行“你好啊”
[email protected]:~/linux/sed
oh, is it?
yes
[email protected]:~/linux/sed
oh, is it?
yes
8,在第一行和第二行的后面,增加一行
[email protected]:~/linux/sed$ sed ‘1,2a learning how to use sed command’ ghostwu.txt this is ghostwu
learning how to use sed command
how are you
learning how to use sed command
fine thank you
9,也可以增加多行
[email protected]:~/linux/sed sed ‘1a 你好啊\n很高兴认识你’ ghostwu.txt
this is ghostwu
你好啊
很高兴认识你
how are you
fine thank you
10, c为替换操作,数字的意思,跟上面的a一样,代表行
[email protected]:~/linux/sed sed ‘1,2c hey guy’ ghostwu.txt
hey guy
fine thank you
[email protected]:~/linux/sed$ sed ‘1c hey guy’ ghostwu.txt
hey guy
how are you
fine thank you
11, s:替换匹配到的内容, s:替换开始 /is/ 匹配包含is的行 g:全部替换
[email protected]:~/linux/sed sed ‘s/is/IS/’ ghostwu.txt
thIS is ghostwu
how are you
fine thank you
[email protected]:~/linux/sed cat ghostwu.txt
this is ghostwu
how are you
fine thank you
12、-i :修改,插入文件,会影响文件的内容,在最后一行,插入bye bye
[email protected]:~/linux/sed sed -i ' cat ghostwu.txt
this is ghostwu
how are you
fine thank you
bye bye
13,在1-3行,每一行的后面都插入一行数字
[email protected]:~/linux/sed sed -i ‘1,3a 123457’ ghostwu.txt
[email protected]:~/linux/sed$ cat ghostwu.txt
this is ghostwu
123457
how are you
123457
fine thank you
123457
bye
上一篇: Linux下Quagga安装与配置
下一篇: Go学习笔记--Map基础