上周与你们分享了30个Linux使用技巧,可是还不够!今天又总结了一些,在学习Linux的路上但愿能帮到你。
上篇:《30个必知的Linux命令技巧,你都掌握了吗?》 html
#要安装inotify-tools软件包 #!/bin/bash MON_DIR=/opt inotifywait -mq --format %f -e create $MON_DIR |\ while read files; do echo $files >> test.log done
# find ./ -name '*.jpg' -o -name '*.png' # find ./ -regex ".*\.jpg\|.*\.png"
# echo "hello" |awk -F '' '{for(i=1;i<=NF;i++)print $i}' # echo "hello" |sed 's/./&\n/g' # echo "hello" |sed -r 's/(.)/\1\n/g'
# watch -d -n 1 'ifconfig'
linux
# echo `echo "content" | iconv -f utf8 -t gbk` | mail -s "`echo "title" | iconv -f utf8 -t gbk`" xxx@163.com 注:经过iconv工具将内容字符集转换
# sed '4~3s/^/\n/' file # awk '$0;NR%3==0{print "\n"}' file # awk '{print NR%3?$0:$0 "\n"}' file
# sed '/abc/,+1d' file #删除匹配行及后一行 # sed '/abc/{n;d}' file #删除后一行 # tac file |sed '/abc/,+1d' |tac #删除前一行
效率1 # wc -l file 效率2 # grep -c . file 效率3 # awk 'END{print NR}' file 效率4 # sed -n '$=' file
# sed -i 's/^[ \t]*//;s/[ \t]*$//' file
windows
# echo '10.10.10.1 10.10.10.2 10.10.10.3' |sed -r 's/[^ ]+/"&"/g' # echo '10.10.10.1 10.10.10.2 10.10.10.3' |awk '{for(i=1;i<=NF;i++)printf "\047"$i"\047"}'
wait(){ echo -n "wait 3s" for ((i=1;i<=3;i++)); do echo -n "." sleep 1 done echo } wait
# awk 'NR==1{next}{print $0}' file #$0可省略 # awk 'NR!=1{print}' file # awk 'NR!=1{print $0}' 或删除匹配行:awk '!/test/{print $0}' # sed '1d' file # sed -n '1!p' file
在第二行前一行加txt: # awk 'NR==2{sub('/.*/',"txt\n&")}{print}' a.txt # sed'2s/.*/txt\n&/' a.txt 在第二行后一行加txt: # awk 'NR==2{sub('/.*/',"&\ntxt")}{print}' a.txt # sed'2s/.*/&\ntxt/' a.txt
# ifconfig |awk -F'[: ]' '/^eth/{nic=$1}/192.168.18.15/{print nic}'
bash
# awk 'BEGIN{print 46/100}' 0.46 # echo 46|awk '{print $0/100}' 0.46 # awk 'BEGIN{printf "%.2f\n",46/100}' 0.46 # echo 'scale=2;46/100' |bc|sed 's/^/0/' 0.46 # printf "%.2f\n" $(echo "scale=2;46/100" |bc) 0.46
方法1: if [ $(echo "4>3"|bc) -eq 1 ]; then echo yes else echo no fi 方法2: if [ $(awk 'BEGIN{if(4>3)print 1;else print 0}') -eq 1 ]; then echo yes else echo no fi
$ cat a.txt 1: 2 3 替换后:1,2,3 方法1: $ tr '\n' ',' < a.txt $ sed ':a;N;s/\n/,/;$!b a' a.txt $ sed ':a;$!N;s/\n/,/;t a' a.txt : 方法2: while read line; do a+=($line) done < a.txt echo ${a[*]} |sed 's/ /,/g' 方法3: awk '{s=(s?s","$0:$0)}END{print s}' a.txt #三目运算符(a?b:c),第一个s是变量,s?s","$0:$0,第一次处理1时,s变量没有赋值为假,结果打印1,第二次处理2时,s值是1,为真,结果1,2。以此类推,小括号能够不写。 awk '{if($0!=3)printf "%s,",$0;else print $0}' a.txt
方法1:打开文件后输入 :set fileformat=unix 方法2:打开文件后输入 :%s/\r*$// #^M可用\r代替 方法3: sed -i 's/^M//g' a.txt #^M的输入方式是ctrl+v,而后ctrl+m 方法4: dos2unix a.txt
xargs -n1 #将单个字段做为一行 # cat a.txt 1 2 3 4 # xargs -n1 < a.txt 1 2 3 4
xargs -n2 #将两个字段做为一行 $ cat b.txt string number a 1 b 2 $ xargs -n2 < a.txt string number a 1 b 2
方法1: # find . -name "*.html" -maxdepth 1 -exec du -b {} \; |awk '{sum+=$1}END{print sum}' 方法2: for size in $(ls -l *.html |awk '{print $5}'); do sum=$(($sum+$size)) done echo $sum 递归统计: # find . -name "*.html" -exec du -k {} \; |awk '{sum+=$1}END{print sum}'