亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

目錄
2. Using awk for Field-Based Text Processing
Basic awk Syntax
3. Combining sed and awk
4. Practical Examples
首頁 系統(tǒng)教程 Linux 如何在Linux中使用`sed'和`awk'進(jìn)行文本處理

如何在Linux中使用`sed'和`awk'進(jìn)行文本處理

Jul 29, 2025 am 01:59 AM

sed和awk是Linux中強(qiáng)大的文本處理工具,適用於命令行下的高效文本操作,用於日誌解析、配置文件編輯和數(shù)據(jù)轉(zhuǎn)換。 1. sed用於流編輯,可進(jìn)行文本替換(如s/old/new/替換首次出現(xiàn),s/old/new/g全局替換),在特定行操作(如3s/old/new/僅第3行,2,5s/old/new/g第2到5行),刪除行(/^$/d刪空行,/error/d刪含error的行),插入或追加文本(/start/i\New line before在匹配前行插入,/end/a\New line after在匹配後行追加),使用-i選項可直接修改文件,建議用其他分隔符如|避免路徑替換時的“slash hell”。 2. awk擅長基於字段的文本處理,基本語法為awk 'pattern { action }' file.txt,默認(rèn)以空白分隔字段,可打印指定字段({print $1, $3}),使用-F指定分隔符(-F','處理CSV,-F':'處理passwd文件),支持模式過濾($2 == "active"打印第二字段為active的行,/error/匹配含error的行並打印行號NR),可進(jìn)行計算({sum = $2} END {print "Total:", sum}求和),添加條件與格式化輸出($3 > 100 {print $1 " is over budget"}),內(nèi)置變量包括NR(當(dāng)前行號)、NF(當(dāng)前行字段數(shù))、FILENAME(文件名),如{print NR ". " $0 " (fields: " NF ")"}。 3. sed和awk可結(jié)合使用,通過管道實現(xiàn)複雜處理:先用sed清理文本再awk處理,如sed 's/^\[ \\t\]\*//; s/\[ \\t\]\*$//' file.txt | awk '$2 > 50 {print $1}'去除首尾空白後打印第二字段大於50的第一字段;或awk提取字段後sed追加內(nèi)容,如awk -F'|' '{print $2, $4}' data.txt | sed 's/$/ added/'。 4. 實際應(yīng)用包括:提取日誌中的IP並統(tǒng)計grep -oE '\b([0-9]{1,3}\.){3}[0-9]{1,3}\b' access.log | sort | uniq -c,再用awk '$1 > 100 {print $2}'篩選訪問超100次的IP;安全修改配置文件sed -i.bak 's/^#\(Port 22\)/\1/' /etc/ssh/sshd_config取消註釋Port 22並備份原文件;格式化ps輸出ps aux | awk '$3 > 5.0 {print $1, $2, $3, $11}' | head -10列出CPU使用超5%的前10個進(jìn)程??傊?,處理文本流時用sed,分析結(jié)構(gòu)化數(shù)據(jù)時用awk,兩者結(jié)合可大幅提升命令行文本處理效率。

How to Use `sed` and `awk` for Text Processing in Linux

sed and awk are two of the most powerful text-processing tools in Linux. They allow you to manipulate text efficiently from the command line, making them essential for log parsing, configuration file editing, and data transformation. Here's how to use them effectively.

How to Use `sed` and `awk` for Text Processing in Linux

1. Using sed for Stream Editing

sed (stream editor) is ideal for performing basic text transformations on an input stream (a file or input from a pipeline).

Common sed Operations

  • Substitute text
    Replace the first occurrence of a pattern on each line:

    How to Use `sed` and `awk` for Text Processing in Linux
     sed 's/old/new/' file.txt

    Replace all occurrences:

     sed 's/old/new/g' file.txt
  • Replace on specific lines
    Only replace on line 3:

    How to Use `sed` and `awk` for Text Processing in Linux
     sed '3s/old/new/' file.txt

    Replace in a range (lines 2 to 5):

     sed '2,5s/old/new/g' file.txt
  • Delete lines
    Delete blank lines:

     sed '/^$/d' file.txt

    Delete lines containing a pattern:

     sed '/error/d' file.log
  • Insert or append text
    Insert a line before a match:

     sed '/start/i\New line before' file.txt

    Append a line after a match:

     sed '/end/a\New line after' file.txt
  • Edit files in place
    Use -i to save changes directly:

     sed -i 's/foo/bar/g' config.txt

? Tip: Use a different delimiter (like | ) to avoid "slash hell" when working with paths:

 sed 's|/home/user|/tmp|g' file.txt

2. Using awk for Field-Based Text Processing

awk excels at processing structured text (like CSV or log files), where data is organized in fields.

Basic awk Syntax

 awk 'pattern { action }' file.txt
  • Print specific fields
    By default, fields are separated by whitespace. Print the first and third fields:

     awk '{print $1, $3}' data.txt
  • Use a custom delimiter
    For comma-separated values:

     awk -F',' '{print $2}' users.csv

    Or with a colon (eg, /etc/passwd ):

     awk -F':' '{print $1, $6}' /etc/passwd
  • Filter lines with patterns
    Print lines where the second field equals "active":

     awk '$2 == "active" {print $0}' status.txt

    Print lines containing the word "error":

     awk '/error/ {print NR, $0}' app.log
  • Perform calculations
    Sum values in the second column:

     awk '{sum = $2} END {print "Total:", sum}' numbers.txt
  • Add conditions and formatting

     awk '$3 > 100 {print $1 " is over budget"}' expenses.txt
  • Built-in variables

    • NR – Current record (line) number
    • NF – Number of fields in the current line
    • FILENAME – Name of the input file

    Example:

     awk '{print NR ". " $0 " (fields: " NF ")"}' data.txt

3. Combining sed and awk

You can pipe sed and awk together for advanced processing:

  • Clean up text with sed , then process with awk :

     sed 's/^[ \t]*//; s/[ \t]*$//' file.txt | awk '$2 > 50 {print $1}'

    (Removes leading/trailing whitespace, then prints first field if second field > 50)

  • Extract and reformat data:

     awk -F'|' '{print $2, $4}' data.txt | sed 's/$/ added/'

    (Prints fields 2 and 4, then appends " added" to each line)


4. Practical Examples

  • Extract IPs from a log and count occurrences:

     grep -oE '\b([0-9]{1,3}\.){3}[0-9]{1,3}\b' access.log | sort | uniq -c

    Then use awk to filter suspicious ones:

     awk '$1 > 100 {print $2}' # IPs accessed more than 100 times
  • Modify configuration files safely:

     sed -i.bak 's/^#\(Port 22\)/\1/' /etc/ssh/sshd_config

    (Uncomments "Port 22" and creates a backup)

  • Format output from ps :

     ps aux | awk '$3 > 5.0 {print $1, $2, $3, $11}' | head -10

    (Lists top 10 processes with CPU > 5%)


Both tools are scriptable and can handle complex logic, but for quick command-line text manipulation, even simple one-liners save a lot of time. Start with basic substitutions and field printing, then build up as needed.

Basically, if you're editing text streams — use sed . If you're analyzing or reporting on structured data — reach for awk .

以上是如何在Linux中使用`sed'和`awk'進(jìn)行文本處理的詳細(xì)內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Laravel 教程
1597
29
PHP教程
1488
72
如何在Linux機(jī)器上解決DNS問題? 如何在Linux機(jī)器上解決DNS問題? Jul 07, 2025 am 12:35 AM

遇到DNS問題時首先要檢查/etc/resolv.conf文件,查看是否配置了正確的nameserver;其次可手動添加如8.8.8.8等公共DNS進(jìn)行測試;接著使用nslookup和dig命令驗證DNS解析是否正常,若未安裝這些工具可先安裝dnsutils或bind-utils包;再檢查systemd-resolved服務(wù)狀態(tài)及其配置文件/etc/systemd/resolved.conf,並根據(jù)需要設(shè)置DNS和FallbackDNS後重啟服務(wù);最後排查網(wǎng)絡(luò)接口狀態(tài)與防火牆規(guī)則,確認(rèn)53端口未

您將如何調(diào)試速度慢或使用高內(nèi)存使用量的服務(wù)器? 您將如何調(diào)試速度慢或使用高內(nèi)存使用量的服務(wù)器? Jul 06, 2025 am 12:02 AM

發(fā)現(xiàn)服務(wù)器運行緩慢或內(nèi)存佔用過高時,應(yīng)先排查原因再操作。首先要查看系統(tǒng)資源使用情況,用top、htop、free-h、iostat、ss-antp等命令檢查CPU、內(nèi)存、磁盤I/O和網(wǎng)絡(luò)連接;其次分析具體進(jìn)程問題,通過ps、jstack、strace等工具追蹤高佔用進(jìn)程的行為;接著檢查日誌和監(jiān)控數(shù)據(jù),查看OOM記錄、異常請求、慢查詢等線索;最後根據(jù)常見原因如內(nèi)存洩漏、連接池耗盡、緩存失效風(fēng)暴、定時任務(wù)衝突進(jìn)行針對性處理,優(yōu)化代碼邏輯,設(shè)置超時重試機(jī)制,加限流熔斷,並定期壓測評估資源。

在Ubuntu中安裝用於遠(yuǎn)程Linux/Windows訪問的鱷梨調(diào)味醬 在Ubuntu中安裝用於遠(yuǎn)程Linux/Windows訪問的鱷梨調(diào)味醬 Jul 08, 2025 am 09:58 AM

作為系統(tǒng)管理員,您可能會發(fā)現(xiàn)自己(今天或?qū)恚┰赪indows和Linux並存的環(huán)境中工作。 有些大公司更喜歡(或必須)在Windows Box上運行其一些生產(chǎn)服務(wù)已不是什麼秘密

如何在Linux中找到我的私人和公共IP地址? 如何在Linux中找到我的私人和公共IP地址? Jul 09, 2025 am 12:37 AM

在Linux系統(tǒng)中,1.使用ipa或hostname-I命令可查看私有IP;2.使用curlifconfig.me或curlipinfo.io/ip可獲取公網(wǎng)IP;3.桌面版可通過系統(tǒng)設(shè)置查看私有IP,瀏覽器訪問特定網(wǎng)站查看公網(wǎng)IP;4.可將常用命令設(shè)為別名以便快速調(diào)用。這些方法簡單實用,適合不同場景下的IP查看需求。

如何在Rocky Linux 8上安裝Nodejs 14/16&npm 如何在Rocky Linux 8上安裝Nodejs 14/16&npm Jul 13, 2025 am 09:09 AM

Node.js建立在Chrome的V8引擎上,是一種開源的,由事件驅(qū)動的JavaScript運行時環(huán)境,用於構(gòu)建可擴(kuò)展應(yīng)用程序和後端API。 Nodejs因其非阻滯I/O模型而聞名輕巧有效,並且

安裝Linux的系統(tǒng)要求 安裝Linux的系統(tǒng)要求 Jul 20, 2025 am 03:49 AM

LinuxCanrunonModestHardwarewtareWithSpecificminimumRequirentess.A1GHZPROCESER(X86ORX86_64)iSNEDED,withAdual-Corecpurecommondend.r AmshouldBeatLeast512MbForCommand-lineUseor2Gbfordesktopenvironments.diskSpacePacereQuiresaminimumof5-10GB,不過25GBISBISBETTERFORAD

20 yum命令用於Linux軟件包管理 20 yum命令用於Linux軟件包管理 Jul 06, 2025 am 09:22 AM

在本文中,我們將學(xué)習(xí)如何使用RedHat開發(fā)的YUM(黃狗更新程序修改)工具在Linux系統(tǒng)上安裝,更新,查找軟件包,管理軟件包和存儲庫。 本文顯示的示例命令是實用的

如何在Rocky Linux和Almalinux上安裝MySQL 8.0 如何在Rocky Linux和Almalinux上安裝MySQL 8.0 Jul 12, 2025 am 09:21 AM

MySQL用C編寫,是一個開源,跨平臺,也是使用最廣泛的關(guān)係數(shù)據(jù)庫管理系統(tǒng)(RDMS)之一。這是LAMP堆棧不可或缺的一部分,是Web託管,數(shù)據(jù)分析,數(shù)據(jù)庫管理系統(tǒng),數(shù)據(jù)分析,

See all articles