上週與你們分享了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}'