您的位置:首页 > 运维架构 > Shell

linux shell sed awk 命令(1)-sed

2016-12-11 23:25 363 查看
linux shell sed awk 命令(1)-sed

sed [选项]... {脚本指令} [输入文件]
-n,--quiet,--silent 静默输出,该选项可以屏蔽自动打印
-e 允许多个脚本命令被执行
-f 从文件中读取脚本指令
-i,--in-place 直接修改源文件
-l N 可以输出行的长度
--posix 禁用GUN sed扩展功能
-r 在脚本中使用扩展正则表达式
-s,--separate 默认情况下sed将把输入的多个文件名作为一个长的连续的输入流.
GUN sed 允许把他们当做单独的文件
-u,--unbuffered 最低限度的缓存输入与输出

eg:
sed '2a TYPE=Ethernet' eth0 第二行后追加
sed '3i TYPE=Ethernet ' eth0 第三行前插入
sed 's/yes/no/g' eth0 将文本中的yes替换成no
sed '3,4d' eth0 删除第三行和第四行
sed '/^GATEWAY/d' eth0 删除geteway的行
sed 's/yes/no/g;s/static/dhcp/g' eth0
sed -e 's/yes/no/g' -e 's/static/dhcp/g' eth0  命令效果如上面命令一样
sed -f sed_command.sh eth0 使用sed_command.sh中的命令进行操作
sed_command 内容如下:
/^$/d

sed -n '2p' eth0  
sed -n '1~2p' eth0 打印文件中奇数数行
sed '2,8d' eth0 删除2~8之间所有行

sed 常用命令汇总
s 替换
a 追加
c 更改
y 按字符串替换
p 打印
w 保存至文件
d 删除
i 插入
l 打印,显示非打印字符
L 打印,不显示非打印字符
r 读入文件内容
q 退出

eg:
(1)给html文件中第二个body 追加/
1.test.html
内容如下:
<html>
<title>test Web</title>
<body>Hello world! <body>
</html>

2.command.sh
内容如下:
/body/{
s//\/body/2
}

3.sed -f sed_command.sh test.html
<html>
<title>test Web</title>
<body>Hello world! </body>
</html>

(2)给所有第一个的h1,h2等添加<>;第二个h1,h2添加</>
test.html 内容如下:

<html>
<title>test Web</title>
<body>
h1Helloh1
h2Helloh2
h3Helloh3
</body>
</html>

2. sed_command.sh内容如下:
/h[0-9]/{
s//\<&\>/1
s//\<\/&\>/2
}

3. sed -f sed_command.sh test.html
<html>
<title>test Web</title>
<body>
<h1>Hello</h1>
<h2>Hello</h2>
<h3>Hello</h3>
</body>
</html>

(3)sed '/ONBOOT/c ONBOOT=yes' eth0

(4)
1.test.test内容如下:
aaa
bbb
ccc
ddd
eee
fff
2. sed '/.*/N;L' test.test
aaa bbb
aaa
bbb
ccc ddd
ccc
ddd
eee fff
eee
fff

sed '/.*/N;P' test.test
sed '/.*/N;p' test.test

(5)
1.sed_test.sh 内容如下:
#n
/222/{
N
l
}
2.sed_test 内容如下:
111
222
222
222
333
3.sed -f sed_test.sh sed_test
222\n222$
222\n333$

Hold (h,H),Get(g,G)
Hold(h|H) 将模式空间的内容复制或追加到保持空间
Get(g|G) 将保持空间的内容复制或追加到模式空间
Exchange(x) 交换保持空间与模式空间

eg:
sed_command内容如下:
/aaa/{
h
d
}

test.test内容如下:aaabbbcccdddeeefff

sed -f sed_command.sh test.test
bbb
ccc
ddd
eee
fff
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  linux sed shel