Linux中sed和awk用法

--------------------sed------
sed    #經過指定的正則表達式完成指定關鍵字的過濾、截取、修改等操做
sed '1,3d' passwd    #將 passwd 的第 1-3 行刪除
sed -n '/^[Rr]oot/p' passwd    #查找以R或r開頭且後面字符爲oot的行
    ---不加-n則顯示全部行
sed -n ‘/root/p’ passwd    #打印匹配字段的行
sed '1d' passwd    #默認刪除第一行
sed '4,$d' passwd #默認刪除第 4 行至末尾行
sed '/root/d' passwd    #刪除含有指定字符串的行
sed –n 's/root/Linux/p’ passwd    #將全部行第一個出現的root換爲Linux
sed -n 's/root/Linux/gp' passwd    #將文件中全部出現的root換爲Linux    
sed 's/bash$/&.linux/p' passwd    #將行尾爲bash的行後追加.linux
sed -n 's/bash$/linux/gp' passwd    #將全部行行尾爲bash換爲linux
sed -n '/root/,/bin/p' passwd    #顯示全部含有root及bin的行
sed -n '1,/adm/p' passwd    #從第一行開始顯示至包含adm的行
 
多點編輯方法
sed -e '2d' -e 's/root/linux/g' passwd    
        # 刪除第二行並將全部root換爲linux
sed -ne '5,6p' -e '/root/p'  passwd    #打印第五、6行,並打印含有root的行
sed '/root/r /etc/fstab' passwd    #查找含有root的行並追加文件內容
sed '/root/w 1.txt' passwd    #將含root的行>到1.txt
sed '/root/a\--linux--' passwd    #含有root的行下加入"--linux--"
sed 's/root/ROOT/g' passwd    #將全部小寫的root改成大寫
sed ‘y/root/ROOT/’ passwd    #將r、o、o、t字符分別換爲R、O、O、T
 
---------------awk+-------------cut
cut
    -d    指定分隔符
    -f    顯示第幾列
cut -d ":" -f 1 passwd
 
awk    # 經過正則表達式 , 獲得須要的行 , 列信息
awk '/root/' passwd    #打印全部包含有 root 字段的行
df -h |awk '{print $2}'    #打印df -h的第二列內容
df -h |awk '{print $2,$5}'    #打印df -h的第二列和第五列
awk 'NR==4' passwd    #顯示文件的第四行
df -h |awk '/\/dev\/sda2/ {print $2}'    #打印df -h含有/dev/sda2的行的第二區域
    \爲轉義符號 ---忽略符號的原有含義
date | awk ‘{print 「Year:」 $6 「\nMonth:」 $2 }’
    #顯示年月信息,\n 爲換行符
df -h|awk '/dev/ {print NR,$2}'    # 匹配含有dev的行 顯示行號並打印第二列
awk -F ":" '{print $2}' # 以:爲分隔符打印第二列
 
 
awk 認爲文件中每一行是一條記錄 記錄與記錄的分隔符爲空
awk [命令選項] `{}` [fliename]
-F fs    指定文件分隔符
-f file    指定讀取程序的文件名
awk '{print $1}' file
awk '{print $NF}' file
awk '{print $1,$3,$5}' file
head -l /etc/passwd | awk -F: '{print $1 "-" $3"-"$5}'
awk 'NR==3{print $0}NR==5{print $0}' file
awk -F : 'NR==1{print $1}' /etc/passwd
BEGIN END
awk 'BEGIN{print "hello"}{print $0}' file
awk 'END{print "hello"}{print $0}' file
awk 'BEGIN{print 100*100/20}'
awk 'BEGIN{A=1;B=2;print A+B}'
awk 'BEGIN{print 20^3}'
awk 'NR==1{t=$2}NR==2{f=$2;pfrint (t-f)*100/t}' /proc/meminfo |grep -F. '{print $1}'
+=累加
vim aa
1
2
3
4
awk '{sum += $1}END{print sum}' aa
cat /proc/25399/smaps |grep Rss|awk '{sum += $2}END{print sum}'
條件運算
比較運算
awk '$1>=2{print $0}' aa
awk '$1==2{print $0}' aa
awk '$1!=2{print $0}' aa
awk '$1<2{print $0}' aa
awk -F: '$1=="root"{print $0}' /etc/passwd
awk -F: '$1!="root"{print $0}' /etc/passwd
awk -F: '$1 ~ "ro"{print $0}' /etc/passwd
awk -F: '$1 ~ "^ro"{print $0}' /etc/passwd
相關文章
相關標籤/搜索