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

目錄
What Are sed and awk ?
2. Replace on Specific Lines
3. Delete Lines
4. Insert or Append Text
5. Save Changes to File
Practical Uses of awk
1. Print Specific Columns
2. Use a Custom Field Separator
3. Filter Rows Based on Conditions
4. Process Headers and Summarize Data
5. Format Output with Labels
Combining sed and awk in Pipelines
Common Pitfalls and Tips
Final Thoughts
首頁 系統(tǒng)教程 Linux 在Linux中使用' SED”和' AWK”的實用指南

在Linux中使用' SED”和' AWK”的實用指南

Jul 27, 2025 am 02:01 AM
sed awk

sed和awk是Linux/Unix系統(tǒng)中強大的文本處理工具,sed用於流式編輯,適合查找替換、刪除插入等操作,awk則是完整的文本處理語言,擅長字段提取、條件過濾和數(shù)據(jù)計算。 1. sed常用功能包括:使用s/old/new/g全局替換文本,3s///在指定行替換,/pattern/s///在匹配行替換,d刪除特定行(如/^$/d刪空行),i和a在指定位置插入或追加文本,-i參數(shù)可保存修改到文件並用-i.bak備份原文件。 2. awk常用功能包括:{print $1,$3}打印指定列,-F','設(shè)置分隔符處理CSV,$2>30按條件過濾行,NR>1跳過頭部,{sum =$2} END{print sum}求和統(tǒng)計,END{print NR}計數(shù),以及print "Label: "$1格式化輸出。 3. 可通過管道組合二者,如cat log | sed 's/.*] "\(GET|POST\) .*" //' | awk '{print $1}' | sort | uniq -c | sort -nr清洗日誌並統(tǒng)計IP訪問次數(shù)。 4. 使用時應(yīng)避免常見錯誤:用單引號防止shell擴展,sed中可換分隔符如s|old|new|g避免路徑衝突,awk支持變量和編程結(jié)構(gòu),修改前先預(yù)覽不加-i,注意正則表達式中.和*的特殊含義。掌握sed和awk能顯著提昇文本處理效率,適用於自動化、日誌分析和數(shù)據(jù)清洗,常可替代更複雜的Python或Perl腳本。

A Practical Guide to Using `sed` and `awk` in Linux

sed and awk are two of the most powerful text-processing tools in Linux and Unix-like systems. While they may seem cryptic at first, mastering them can dramatically improve your efficiency when working with text files, logs, configuration files, and data streams. This guide breaks down practical uses of both tools with real-world examples, focusing on day-to-day tasks.

A Practical Guide to Using `sed` and `awk` in Linux

What Are sed and awk ?

  • sed (Stream Editor) : Processes text line by line. It's ideal for find-and-replace, inserting or deleting lines, and basic text transformations.
  • awk (Named after its creators: Aho, Weinberg, and Kernighan) : A full scripting language for text processing. It excels at working with structured data (like CSVs), extracting fields, and performing calculations.

They're often used together in pipelines to filter, transform, and analyze text efficiently.


Practical Uses of sed

sed works on streams — it reads input, applies edits, and outputs the result. By default, it doesn't modify the original file unless told to.

A Practical Guide to Using `sed` and `awk` in Linux

1. Find and Replace Text

The most common use of sed is replacing text using the s (substitute) command.

 sed 's/old-text/new-text/' filename

Example: Replace all instances of "apple" with "orange" in a file:

A Practical Guide to Using `sed` and `awk` in Linux
 sed 's/apple/orange/' fruits.txt

?? This only replaces the first occurrence per line. To replace all occurrences, add the g (global) flag:

 sed 's/apple/orange/g' fruits.txt

2. Replace on Specific Lines

You can limit substitutions to certain lines.

  • Replace only on line 3:

     sed '3s/apple/orange/' fruits.txt
  • Replace only in lines containing "fruit":

     sed '/fruit/s/apple/orange/' fruits.txt

3. Delete Lines

Use the d command to remove lines.

  • Delete line 5:

     sed '5d' file.txt
  • Delete all blank lines:

     sed '/^$/d' file.txt
  • Delete lines containing "error":

     sed '/error/d' log.txt

4. Insert or Append Text

  • Insert "Header" before line 1:

     sed '1i\Header' file.txt
  • Append "Footer" after line 1:

     sed '1a\Footer' file.txt

5. Save Changes to File

By default, sed outputs to stdout. To edit a file in place, use -i :

 sed -i 's/apple/orange/g' fruits.txt

? Use -i.bak to create a backup before editing:

 sed -i.bak 's/apple/orange/g' fruits.txt

Practical Uses of awk

awk treats each line as a record and splits it into fields. By default, fields are separated by whitespace.

1. Print Specific Columns

Print the first and third fields from each line:

 awk '{print $1, $3}' data.txt

Useful for log files or CSV-like data.

Example input ( data.txt ):

 John 25 Engineer
Jane 30 Designer
Bob 35 Manager

Command:

 awk '{print $1, $3}' data.txt

Output:

 John Engineer
Jane Designer
Bob Manager

2. Use a Custom Field Separator

For CSV files, use -F to define the delimiter:

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

For tab-separated files:

 awk -F'\t' '{print $1}' data.tsv

3. Filter Rows Based on Conditions

Print lines where the second field is greater than 30:

 awk '$2 > 30' data.txt

Print lines where the first field is "Jane":

 awk '$1 == "Jane"' data.txt

Combine conditions:

 awk '$2 > 25 && $3 == "Engineer"' data.txt

4. Process Headers and Summarize Data

Skip the header line:

 awk 'NR > 1 {print}' file.csv

NR = Number of Records (line number)

Sum values in a column:

 awk '{sum = $2} END {print "Total:", sum}' numbers.txt

Count lines:

 awk 'END {print NR}' file.txt

5. Format Output with Labels

 awk '{print "Name: " $1 ", Age: " $2}' data.txt

Output:

 Name: John, Age: 25
Name: Jane, Age: 30

Combining sed and awk in Pipelines

You can chain both tools for advanced processing.

Example: Clean a log file, extract IP addresses, and count occurrences:

 cat access.log | \
sed 's/.*\] "\(GET\|POST\) .*" //' | \
awk '{print $1}' | \
sort | uniq -c | sort -nr

Breakdown:

  • sed : Removes log prefix and HTTP request line
  • awk : Extracts first field (IP)
  • sort | uniq -c : Counts unique IPs
  • Final sort -nr : Sorts by count descending

Common Pitfalls and Tips

  • Use single quotes around sed and awk scripts to avoid shell expansion.
  • In sed , the delimiter in s/// can be changed (eg, s|old|new|g ) — useful when working with paths.
  • awk supports variables, loops, and functions — it's a full scripting language.
  • Always test without -i first to preview changes.
  • Be cautious with regex — . and * have special meanings.

Final Thoughts

sed and awk are not just legacy tools — they're fast, lightweight, and perfect for automation, log parsing, and data munging. Start with simple substitutions and field extractions, then gradually explore pattern matching, conditions, and arithmetic.

Once you're comfortable, you'll find yourself reaching for them instead of writing longer scripts in Python or Perl — especially in shell pipelines.

Basically, if it involves text, sed and awk can probably help.

以上是在Linux中使用' SED”和' AWK”的實用指南的詳細內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願投稿,版權(quán)歸原作者所有。本站不承擔相應(yīng)的法律責任。如發(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

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

Dreamweaver CS6

Dreamweaver CS6

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

SublimeText3 Mac版

SublimeText3 Mac版

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

熱門話題

Laravel 教程
1597
29
PHP教程
1488
72
Linux快速刪除檔案末尾行的操作步驟 Linux快速刪除檔案末尾行的操作步驟 Mar 01, 2024 pm 09:36 PM

Linux系統(tǒng)下在處理檔案時,有時候需要刪除檔案末端的行。這種操作在實際應(yīng)用中很常見,可以透過一些簡單的命令來實現(xiàn)。本文將介紹在Linux系統(tǒng)中快速刪除檔案結(jié)尾行的操作步驟,同時提供具體的程式碼範例。步驟一:檢視文件末尾行在進行刪除操作之前,首先需要確認文件的末尾行是哪一行??梢允褂胻ail指令來查看文件的結(jié)尾行,具體指令如下:tail-n1filena

綜合總結(jié):詳解 Linux sed 多行處理 綜合總結(jié):詳解 Linux sed 多行處理 Jan 05, 2024 pm 04:11 PM

在正常情況下,sed將待處理的行讀入模式空間,腳本中的命令就一條接著一條的對該行進行處理,直到腳本執(zhí)行完畢,然後該行被輸出,模式空間請空;然後重複剛才的動作,文件中的新的一行被讀入,直到文件處理完備。但是,各種各樣的原因,例如用戶希望在某個條件下腳本中的某個命令被執(zhí)行,或者希望模式空間得到保留以便下一次的處理,都有可能使得sed在處理文件的時候不按照正常的流程來進行。這時候,sed設(shè)定了一些進階指令來滿足使用者的要求。如果想要學(xué)習sed的高階指令,首先要了解以下兩個快取區(qū):1、模式空間(patt

如何在Linux中使用awk指令進行日誌分析和處理? 如何在Linux中使用awk指令進行日誌分析和處理? Jul 30, 2023 pm 02:23 PM

如何在Linux中使用awk指令進行日誌分析與處理?簡介:在Linux系統(tǒng)中,awk是一種強大的文本分析和處理工具。它可以用來搜尋和提取文件中的特定內(nèi)容,進行資料格式化,以及執(zhí)行一些簡單但有用的計算。本文將介紹如何在Linux中使用awk指令進行日誌分析和處理,包括常用的awk指令選項和範例程式碼。一、awk指令的基本語法與選項awk指令的基本語法如下:awk

使用awk中的比較運算子進行操作的方法 使用awk中的比較運算子進行操作的方法 Dec 31, 2023 pm 09:35 PM

對於使用awk指令的使用者來說,處理一行文字中的數(shù)字或字串時,使用比較運算子來過濾文字和字串是十分方便的。下面的部分我們介紹"awk"的比較運算子。 awk中的比較運算子是什麼? awk中的比較運算子用於比較字串和或數(shù)值,包括以下類型:符號作用>大於<小於>=大於等於<=小於等於==等於!=不等於some_value~/pattern/如果some_value匹配模式pattern ,則傳回truesome_value!~/pattern/如果some_val

流編輯器(SED):基礎(chǔ) 流編輯器(SED):基礎(chǔ) Mar 20, 2024 pm 03:11 PM

SED,也稱為串流編輯器,是一個非常有用的工具。它用於搜尋特定的單字或模式,然後對該單字或模式進行某些操作,或者換句話說,對其進行轉(zhuǎn)換。在Windows中,SED也稱為「尋找」和「替換」功能。 SED是Ubuntu自備的,所以不需要安裝任何東西;只需開始使用它即可。在本教程中,我們將向您介紹如何使用SED或串流編輯器。 「S」號指揮在SED或串流編輯器中最重要的指令是」s」指令。 “s”代表替代品。語法如下:的/regexp/替換/標誌因此,讓我們使用一個名為”file.txt&amp;#

用awk進行文字或字串的模式篩選方法 用awk進行文字或字串的模式篩選方法 Dec 30, 2023 pm 03:02 PM

在篩選文字時,有時你可能想根據(jù)某個給定的條件或使用一個可被配對的特定模式,去標記某個檔案或數(shù)行字串中的某幾行。使用awk來完成這個任務(wù)是非常容易的,這也正是awk中可能對你有幫助的幾個功能之一。讓我們來看看下面這個例子,比方說你有一個寫有你想要購買的食物的購物清單,其名稱為food_prices.list,它所含有的食物名稱及相應(yīng)的價格如下所示:$catfood_prices. listNoItem_NameQuantityPrice1Mangoes10$2.452Apples20$1.503

如何在Linux中使用sed指令進行日誌分析與處理? 如何在Linux中使用sed指令進行日誌分析與處理? Jul 28, 2023 pm 11:53 PM

如何在Linux中使用sed指令進行日誌分析與處理?引言:在Linux系統(tǒng)中,日誌檔案記錄了系統(tǒng)的運作情況和運行日誌,對於系統(tǒng)管理員來說,對日誌檔案進行分析和處理是非常重要的。其中,sed指令是一種非常強大的文字處理工具,可以在Linux環(huán)境中對日誌檔案進行高效率的分析和處理。本文將介紹如何使用sed指令進行日誌的分析和處理,並提供一些常用的sed指令範例。一

linux的sed指令如何使用 linux的sed指令如何使用 May 18, 2023 pm 10:07 PM

一、sed介紹sed全名為(streameditor)串流編輯器,Sed主要用來自動編輯一個或多個檔案、簡化對檔案的反覆操作、編寫轉(zhuǎn)換程式等,工作流程如下1、sed概述>sed是一種線上的、非互動式的編輯器,它一次處理一行內(nèi)容,它是文字處理中非常好的工具,能夠完美的配合正規(guī)表示式使用,功能不同凡響。處理時,把目前處理的行儲存在暫存緩衝區(qū)中,稱為「模式空間」(patternspace),接著用sed指令處理緩衝區(qū)中的內(nèi)容,處理完成後,把緩衝區(qū)的內(nèi)容送到螢?zāi)?。接著處理下一行,這樣不斷重複,直到文

See all articles