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

shell与awk学习复习例子(循环与字符串截取判断)

2017-11-10 15:24 721 查看
1、采集sflow数据脚本

通过sflowrt解析sflow报文,然后通过sflowrt接口json数据获取需要的监控值。


#!/bin/sh

curl_result=`curl http://localhost:8008/metric/10.0.2.4/json 2>/dev/null`
fiter_str=$1
result=`echo $curl_result | awk -F , -v awk_fiter=$fiter_str '{for(i=0;i<NF;i++){ if(index($(i+1),awk_fiter))print $(i+1)}}'`

value=`echo $result| awk -F : '{print $2}'`
echo $value


复习知识:不输出标准错误;awk分割域;awk外部变量赋值给内部自定义变量;awk for与if语句;NF变量;index函数使用。


2、判断挂载在操作系统上的文件系统是否可写脚本

#!/bin/bash

for tmpPath in `df -h | grep '%' |awk 'NR!=1 { for(i=0; i<NF;i++){if($i ~/%$/) print $(i+1)}}'`
do
if `echo "hello" > ${tmpPath}"/hello.txt" `; then
echo $tmpPath "write"
rm ${tmpPath}"/hello.txt"
else
echo $tmpPath "not write"
fi
done


复习知识:shell for和if语句;awk NR变量与~匹配操作符用法。


3、判断文件系统目录属性

由2例子变化而来


#!/bin/bash

for tmpPath in `df -h | grep '%' |awk 'NR!=1 { for(i=0; i<NF;i++){if($i ~/%$/) print $(i+1)}}'`
do
result=`ls -ld ${tmpPath}`
echo $result
p_result=`echo $result |awk '{aaa=$1;print aaa;aa1=substr(aaa,2,1);print aa1;if(aa1 ~ /r/) print "read";print
4000
match(aaa,"^dr")?"read":"not read";print match(aaa,"^d[r-]w")?"wirte":"not wirte"}' `
echo $p_result

done


复习知识:awk substr()函数截取字符串;match函数匹配用法;?操作符用法。


好记性不如烂笔头。网上搜索shell与awk编程例子一大堆,但要做到熟练,随手就用还需要多记多练。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐