sed 範例四

  1. 練習:取出 /etc/man.config 檔案的內容中有 MANPATH 的設定,但其中包含以 "#" 開始的註解,請再利用管線命令以 sed 刪除註解行。
    [dywang@dywmac ~]$ grep MANPATH /etc/man.config
    # when MANPATH contains an empty substring), to find out where the cat
    # MANPATH		manpath_element	[corresponding_catdir]
    # MANPATH_MAP		path_element	manpath_element
    # Every automatically generated MANPATH includes these fields
    MANPATH	/usr/man
    MANPATH	/usr/share/man
    MANPATH	/usr/local/man
    MANPATH	/usr/local/share/man
    MANPATH	/usr/X11R6/man
    # MANPATH	/opt/*/man
    # MANPATH	/usr/lib/*/man
    # MANPATH	/usr/share/*/man
    # MANPATH	/usr/kerberos/man
    # Set up PATH to MANPATH mapping
    MANPATH_MAP	/bin			/usr/share/man
    MANPATH_MAP	/sbin			/usr/share/man
    MANPATH_MAP	/usr/bin		/usr/share/man
    MANPATH_MAP	/usr/sbin		/usr/share/man
    MANPATH_MAP	/usr/local/bin		/usr/local/share/man
    MANPATH_MAP	/usr/local/sbin		/usr/local/share/man
    MANPATH_MAP	/usr/X11R6/bin		/usr/X11R6/man
    MANPATH_MAP	/usr/bin/X11		/usr/X11R6/man
    MANPATH_MAP	/usr/bin/mh		/usr/share/man
    
  2. 取出 /etc/man.config 檔案的內容中有 MANPATH 的設定解答。 且刪除註解說明。
    [dywang@dywmac ~]$ grep MANPATH /etc/man.config | sed '/^#/d'
    MANPATH	/usr/man
    MANPATH	/usr/share/man
    MANPATH	/usr/local/man
    MANPATH	/usr/local/share/man
    MANPATH	/usr/X11R6/man
    MANPATH_MAP	/bin			/usr/share/man
    MANPATH_MAP	/sbin			/usr/share/man
    MANPATH_MAP	/usr/bin		/usr/share/man
    MANPATH_MAP	/usr/sbin		/usr/share/man
    MANPATH_MAP	/usr/local/bin		/usr/local/share/man
    MANPATH_MAP	/usr/local/sbin		/usr/local/share/man
    MANPATH_MAP	/usr/X11R6/bin		/usr/X11R6/man
    MANPATH_MAP	/usr/bin/X11		/usr/X11R6/man
    MANPATH_MAP	/usr/bin/mh		/usr/share/man
    
  3. sed 加參數 -e 同時完成刪除與取代命令。例如: grep -v 取出 /etc/man.config 不是註解的設定行,再利用 sed 刪除檔案第 10 行至最後一行,且將字串 MAN 改成 man
    [dywang@dywmac ~]$ grep -v '^#' /etc/man.config | sed -e '10,$d' -e 's/MAN/man/g'
    FHS
    manPATH	/usr/man
    manPATH	/usr/share/man
    manPATH	/usr/local/man
    manPATH	/usr/local/share/man
    manPATH	/usr/X11R6/man
    manPATH_MAP	/bin			/usr/share/man
    manPATH_MAP	/sbin			/usr/share/man
    manPATH_MAP	/usr/bin		/usr/share/man
    
  4. 如果 sed 要同時執行很多動作,可以將這些動作寫在一個檔案中,再以 -f 選項指令檔案執行 sed 命令。例如將上例刪除與取代命令編輯至檔案 ds.src,執行結果一樣。
    [dywang@dywmac zzz]$ vim ds.src
    [dywang@dywmac zzz]$ cat ds.src
    10,$d
    s/MAN/man/g
    
    [dywang@dywmac zzz]$ grep -v '^#' /etc/man.config | sed -f ds.src 
    FHS
    manPATH	/usr/man
    manPATH	/usr/share/man
    manPATH	/usr/local/man
    manPATH	/usr/local/share/man
    manPATH	/usr/X11R6/man
    manPATH_MAP	/bin			/usr/share/man
    manPATH_MAP	/sbin			/usr/share/man
    manPATH_MAP	/usr/bin		/usr/share/man