linux之awk、sed命令

时间:2023-03-09 02:14:56
linux之awk、sed命令

总结: 两个命令的正则表达式都用''单引号进行区分。

输出变量名用单引号,输出变量值用双引号,这个在bash脚本里一般是通用的。

在bash脚本里要使用变量值,都要加上双引号

awk用法:

参考网址:http://www.cnblogs.com/xudong-bupt/p/3721210.html

命令形式:

awk [-F|-f|-v] ‘BEGIN{} //{command1; command2} END{}’ file

对product_uuid一行以“=”进行分隔,显示第二个参数内容

awk -F "=" '/product_uuid/{print $2}' /etc/save_env

BEGIN、END的使用:

场合:  用于多行的操作

BEGIN 表头  END 表尾。

表头与表尾不可缺少

例如:

awk -F '=' 'BEGIN {print "name,shell"} {print $1,$2} END {print "hello"}'  /etc/save_env

  像{print "name,shell"} 与 {print "hello"} 这两个是必不可少的

save_env文件里行与行之间用&进行连接串起来

awk 'BEGIN {total_str} {total_str=(total_str"&"$1); } END {print total_str}' /etc/save_env

awk 匹配出最大值

awk -F "." '/^P*/{print $4}' /etc/setup/installed.db | awk -F "-" '{print $2}'  | awk 'BEGIN {max=0} {if($1>max)max=$1 fi;}END{print max}'

对一行的内容操作

echo "c,172.16.200.151,1018 ttyS1,115200,8,1,n,0" | awk '{split($0,a,",| ");for (i=1;i<9;i++) print a[i]}'

打印匹配到com2sec的8行数据

awk  '/^com2sec/{i++;if(i<9){print $2}else{exit;}}'  /usr/share/snmp/snmpd.conf

sed 用法:

参考网址:http://www.cnblogs.com/dong008259/archive/2011/12/07/2279897.html

sed [-nefri] 'command'  file

着重说明:如果要直接替换源文件内容而不由屏幕输出,要加上选项 -i,即sed -i

例:删除文件installed.db里ipguard开头的行内容

sed -i '/ipguard/d' setup/installed.db

在某个文件的第3行后或前插入指定内容,如果第3行有内容,则会第3行后插入,如果没有,则直接写入到第3行

参考网址:http://blog.chinaunix.net/uid-15007890-id-3236130.html

sed -i "3i source /opt/mipsel-qtenv.sh" /etc/rc.d/rc.sysinit

在匹配的某一行前添加

notice:第2个i不能存在空格

sed -i '/\/bin\/bash \/etc\/guard_env.sh/i\runmast' /etc/rc.d/rc.sysinit

在匹配的某一行后添加

sed -i '/\/bin\/bash \/etc\/guard_env.sh/a\runmast' /etc/rc.d/rc.sysinit

sed 全局替换,将# module_raw input替换为module_raw input

sed -i "s/# module_raw input/module_raw input/g" /usr/local/qt4-mipsel/mipsel-tslib/etc/ts.conf

sed 局部匹配替换整行

sed -i "/^ifconfig eth0 hw ether/c ifconfig eth0 hw ether F0:FF:95:43:BD:4C" /usr/local/run/A1603_GeneralFs.sh

sed -i "/^::respawn:\/sbin\/getty -L ttyS1 115200 vt100/c ::respawn:\/sbin\/getty -L ttyS10 115200 vt100" /etc/inittab

大括号要加上"\"

sed -i "/^com2sec Read[A-Za-z]\{1,6\} [0-9]/c com2sec $ower_auth $ip $ower_public" /usr/local/snmpd.conf

awk则不用

awk '/^com2sec Read[A-Za-z]{1,6} [0-9]/{print $3}'  /usr/local/snmpd.conf

在指定的第2行后插入

sed -i "2i\com2sec $ower_auth $ip $ower_public" /usr/share/snmp/snmpd.conf

删除的第2行下的1行内容

sed -i '2,1d' /usr/share/snmp/snmpd.conf