2018/01/04

January 4 , 2018

Weather : hight rain !
1、需求:
统计数字并求和
计算文档a.txt中每一行中出现的数字个数并且要计算一下整个文档中一共出现了几个数字。例如a.txt内容如下:
12aa*lkjskdj
alskdflkskdjflkjj

我们脚本名字为 ncount.sh, 运行它时:
bash ncount.sh a.txt
输入结果应该为:
2
0
sum:2

[root@Dasoncheng sbin]# cat t.sh 
#!/bin/bash
##Collect the number and sum ;
sum=0
n=`wc -l 3.txt |awk '{print $1}'`
for i in `seq 1 $n`;
do
  line=`sed -n "$i"p 3.txt`
  n2=`echo -n $line |sed 's/[^0-9]//g' |wc -c`
  echo $i line number: $n2
  sum=$[ $sum + $n2 ]
done
echo "sum:$sum"

2、需求:检测文件改动
有两台Linux服务器A和B,假如A可以直接ssh到B,不用输入密码。A和B都有一个目录叫做/data/web/ 这下面有很多文件,当然我们不知道具体有几层子目录,假若之前A和B上该目录下的文件都是一模一样的。但现在不确定是否一致了。固需要我们写一个脚本实现这样的功能,检测A机器和B机器/data/web/目录下文件的异同,我们以A机器上的文件作为标准。比如,假若B机器少了一个a.txt文件,那我们应该能够检测出来,或者B机器上的b.txt文件有过改动,我们也应该能够检测出来(B机器上多了文件我们不用考虑)。

[aming@Dasoncheng ~]$ cat d.sh 
#!/bin/bash
##test the file changed !
dir=/data/log/
ip=192.168.60.12
find $dir -type f | xargs md5sum >/tmp/md5.txt
ssh root@$ip "find $dir -type f | xargs md5sum > /tmp/md5_2.txt"
scp root@$ip:/tmp/md5_2.txt /tmp/ &>/dev/null
for i in `awk '{print $2}' /tmp/md5_1.txt`
do
  if `grep -q "$i" /tmp/md5_2.txt` ;
  then
      md5_a=`grep "$i" /tmp/md5.txt |awk '{print $1}'`
      md5_b=`grep "$i" /tmp/md5_2.txt |awk '{print $1}'`
      if [ $md5_a != $md5_b ];
      then
          echo "The $i in B has changed"
      fi
  else
      echo "The $i losted"
  fi
done
[aming@Dasoncheng ~]$ sh d.sh 
The /data/log/1.txt in B has changed
The /data/log/2.txt losted
参考答案:

1、

#!/bin/bash

n=`wc -l a.txt|awk '{print $1}'`
sum=0
for i in `seq 1 $n`
do
    line=`sed -n "$i"p a.txt`
    n_n=`echo -n $line|sed 's/[^0-9]//g'|wc -c`
    echo line $i number: $n_n
    sum=$[$sum+$n_n]
done

echo sum is $sum

2、提示: 使用核心命令 md5sum a.txt 算出md5值,去和B机器上的比较。

#!/bin/bash
#假设A机器到B机器已经做了无密码登录设置
dir=/data/web
##假设B机器的IP为192.168.0.100
B_ip=192.168.0.100
find $dir -type f |xargs md5sum >/tmp/md5.txt
ssh $B_ip "find $dir -type f |xargs md5sum >/tmp/md5_b.txt"
scp $B_ip:/tmp/md5_b.txt /tmp
for f in `awk '{print $2}' /tmp/md5.txt`
do
    if grep -q "$f" /tmp/md5_b.txt
    then
        md5_a=`grep $f /tmp/md5.txt|awk '{print $1}'`
        md5_b=`grep $f /tmp/md5_b.txt|awk '{print $1}'`
        if [ $md5_a != $md5_b ]
        then
             echo "$f changed."
        fi
    else
        echo "$f deleted. "
    fi
done

转载于:https://my.oschina.net/u/3651233/blog/1605928

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值