1.日期参数转自定义格式(注意执行命令的符号 ` 和 ‘ 的区别)
yes=$1
echo $yes
mils=`date -d "$yes -1 day" +%s` #参数日期减一天转毫秒
echo $mils
yesterday=`date -d @$mils +%Y/%m/%d` #格式化yyyy/mm/dd形式
echo $yesterday
mils=`date -d "$yes -3 hours -1 day" +%s` # 参数日期减一天和3小时
echo $mils
2.awk字符串处理(注意重定向符左端必有空格)
cat a | awk '{print $NF}' > b # 将a的最后一列截取重定向到b
sort b > c # 对b排序重定向到c
sed -e '/items/d' c > d # 删除c中含有items字符的所有行
awk '{if(NR%2!=0)ORS="\t";else ORS="\n"}1' d > e # 每两行进行合并,并以tab分割
eg:
[a]
Found 2 items
-rwxrwx--- 3 hdfs hdfs 1279029 2018-10-22 22:32 /tmp/1.jhist
-rwxrwx--- 3 hdfs hdfs 142394 2018-10-22 22:32 /tmp/1.xml
Found 2 items
-rwxrwx--- 3 appsearch_dev hdfs 19667953 2018-10-22 00:39 /tmp/2.jhist
-rwxrwx--- 3 appsearch_dev hdfs 142346 2018-10-22 00:39 /tmp/2.xml
[e]
/tmp/1.jhist /tmp/1.xml
/tmp/2.jhist /tmp/2.xml
awk -F , '{print $(NF-1)}' part > cost # 以,分割,拿取倒数第二列重定向到文件cost
awk -F '[:\"]' '{print $(NF-1)}' part >cost # 以:和"分割,注意转义,拿取倒数第二列
awk '{sum += $1};END {print sum}' cost # 对cost第一列做累加并打印结果
3.字符串截取
yes=$1
ymd=`expr substr $1 1 8` # 取1-8字符,substr下标是从1开始
hh=`expr substr $1 9 2` # 从小标为9取2个字符
yes="$ymd $hh" # 拼凑日期,类似20181010 10
4.字符串比较之if语句(注意[]号前后后空格)
yes=$1
mils=`date -d "$yes -3 hours -1 day" +%s`
update_hour=`date -d @$mils +%H`
h23="23"
if [ "$h23" = $update_hour ]; then
#exec your conmand
fi
5.shell做运算(注意括号的使用规范)
#shell脚本数据做运算,数据格式为每行2个数,以除法为例。求出第二个数/第一个数,最后再累加
sum=0
cat test.txt | while read line # while按行读,for会把一行两个数拆分成两行数据
do
time=`echo $line | awk '{print $1}'`
mem=`echo $line | awk '{print $2}'`
res=$(echo "$mem/$time" | bc) #浮点除法,加bc
sum=$(($res+$sum)) #算术运算,使用双括号方式
echo $sum
done