熱門分類
載入中…
目錄0%

🐧 一行搞定!Linux 管線符號與文字處理工具完整教學

    🐧 一行搞定!Linux 管線符號與文字處理工具完整教學

    Linux 的強大之處,不僅在於核心架構,更在於靈活強大的「文字處理生態系」。 從日誌分析、設定檔修改、到自動化批次任務,只要懂得運用 | 管線符號、sedawkgrep 等工具,你幾乎可以用一行指令完成整個流程。

    📘 一、管線符號(|)— 資料流的靈魂

    | 會將前一個指令的「標準輸出(stdout)」直接傳遞給下一個指令的「標準輸入(stdin)」。

    # 顯示登入使用者數量
    who | wc -l
    
    # 篩選出 error 並排序出現頻率
    dmesg | grep "error" | sort | uniq -c | sort -nr | head
    

    🧱 二、cat + EOF:多行輸入快速建立檔案

    所謂 EOF(End Of File)語法是 shell 的 Here Document,能直接在命令中建立多行文字,非常適合自動化腳本。

    cat < /etc/nginx/conf.d/blog.conf
    server {
        listen 80;
        server_name blog.wwfandy.com;
        root /var/www/html;
    }
    EOF
    

    若要同時輸出到畫面與檔案,可結合 tee

    cat </dev/null
    Welcome to WWFandy Linux Server
    Today is $(date)
    EOF
    

    🧩 三、grep:快速搜尋與比對文字

    grep 是最常用的搜尋指令,支援正規表示式。

    grep "root" /etc/passwd             # 搜尋關鍵字
    grep -i "server" nginx.conf         # 忽略大小寫
    grep -n "error" /var/log/syslog     # 顯示行號
    grep -r "Listen" /etc/httpd/        # 遞迴搜尋
    

    ✂️ 四、cut:擷取欄位或字元

    cut 適合用於結構化資料分欄,例如 /etc/passwd

    cut -d: -f1 /etc/passwd   # 取出使用者名稱欄位
    echo "WWFandyBlog" | cut -c1-8
    

    ⚙️ 五、awk:欄位分析與報表輸出

    awk 是 Linux 中最強大的文字分析器之一。

    awk -F: '{printf "%-15s → %s\n",$1,$7}' /etc/passwd
    grep "ERROR" /var/log/syslog | awk '{count++} END {print "Error Count:", count}'
    

    🔧 六、sed:取代、刪除、插入

    sed 可進行即時編修與內容替換。

    sed -i 's/Listen 80/Listen 8080/' /etc/httpd/conf/httpd.conf
    echo "Welcome to Linux" | sed 's/Linux/WWFandy Blog/'
    

    📊 七、wc:快速統計行數、字數與字元

    wc -l file.txt   # 行數
    wc -w file.txt   # 字數
    wc -c file.txt   # 字元數
    grep "http" access.log | wc -l
    

    📑 八、sort + uniq:排序與去重

    cat list.txt | sort | uniq
    cat list.txt | sort | uniq -c | sort -nr | head
    

    🔡 九、tr:字元轉換與清理

    echo "Hello World" | tr 'a-z' 'A-Z'     # 全轉大寫
    cat file.txt | tr -d '\r'               # 移除 CR
    cat file.txt | tr -s ' '                # 合併多重空格
    

    📎 十、paste:橫向合併文件

    paste names.txt phones.txt > contacts.txt

    🚀 十一、xargs:批次執行命令

    find . -name "*.tmp" | xargs rm -f
    grep -rl "localhost" . | xargs sed -i 's/localhost/blog.wwfandy.com/g'
    

    🧭 十二、tee:同時輸出與寫入檔案

    df -h | tee ~/disk_report.txt | grep "root"
    echo "Backup done at $(date)" | tee -a /var/log/backup.log
    

    🧮 十三、綜合實例:自動產出設定與統計

    # 1️⃣ 建立設定檔
    cat < /tmp/service.conf
    service=nginx
    port=80
    status=active
    EOF
    
    # 2️⃣ 修改內容
    sed -i 's/80/8080/' /tmp/service.conf
    
    # 3️⃣ 格式化輸出
    awk -F= '{printf "%-10s : %s\n",$1,$2}' /tmp/service.conf
    
    # 4️⃣ 統計行數
    wc -l /tmp/service.conf
    

    📘 結語

    這些文字處理指令構成了 Linux 的「資料管線生態系」: grep 搜尋、cut 擷取、sed 修改、awk 分析、tee 輸出、xargs 批次執行。 掌握它們的組合,你就能用一行指令完成報表生成、設定自動化與日誌分析,真正體現 Linux 的生產力哲學。


    🔗 延伸閱讀

    — WWFandy・Linux 實作筆記

    🔗 分享這篇 LINE Facebook X

    沒有留言:

    字級