2018/03/26

March 26 2018 Monday

Weather : rainy to cloudy
一、需求:
有兩個文件a.txt和b.txt,須要將a.txt中有的但b.txt中沒有的行找出來,並重定向到c.txt,而後計算c.txt的行數!bash

[root@Dasoncheng sbin]# cat b.sh
#!/bin/bash
##Find the line differents eche other !
[ -f c.txt ] && rm -f c.txt
n=`wc -l a.txt | cut -d " " -f 1`
for i in `seq 1 "$n"` ;
do
  m=`sed -n "$i"p a.txt`
  grep -q $m b.txt
  if [ $? -eq 0 ] ;
  then
      continue
  else
      echo $m >> c.txt
  fi
done
wc -l c.txt

answer referred:

[root@Dasoncheng sbin]# cat b.sh
#!/bin/bash
##Find the line differents eche other !
[ -f c.txt ] && rm -f c.txt
cat a.txt | while read line
do
    if ! grep -q "^$line$" b.txt
    then
           echo $line >> c.txt
    fi
done
wc -l c.txt

或者使用grep -f 實現:code

#!/bin/bash
grep -vwf b.txt a.txt > c.txt
wc -l c.txt
本站公眾號
   歡迎關注本站公眾號,獲取更多信息