使用 sed Linux 命令進行文字和檔案處理


Sed 是一種流編輯器。流編輯器用於對輸入檔案進行常規的文字轉換。在某些方面,它類似於允許指令碼化編輯(如 ed)的編輯器。sed 透過對輸入進行一次遍歷來工作,因此效率更高。現在,讓我們進一步瞭解“使用 sed Linux 命令進行文字和檔案處理”。

首先,要驗證 sed 版本,請使用以下命令:

$ sed --v

示例輸出應如下所示:

sed (GNU sed) 4.2.2
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later .
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
.........................................................................................

In the below example, abc.txt is the file name.

Sed 命令及其描述

序號命令描述
1$sed ‘s/tutorials/tutorialspoint/’ abc.txt將“tutorials”替換為“tutorialspoint”
2$sed ‘$d’ abc.txt刪除 abc.txt 檔案中的最後一行
3$sed ‘s/^[ ^t]*//’ abc.txt刪除 abc.txt 檔案中每行開頭的所有空格
4$sed ‘s/[ ^t]*$//’ file.txt刪除 abc.txt 檔案中每行末尾的所有空格
5$sed ‘s/tutorials/tutorialspoint/p’ abc.txt在 abc.txt 檔案中包含指定字串的行後,列印該行兩次
6$ sed ‘s/tutorialspoint/tutorials/g’ abc.txt這是一個全域性替換命令,用於在 abc.txt 檔案中將“tutorialspoint”替換為“tutorials”
7$ sed -n ‘s/tutorialspoint/tutorials/p’ abc.txt顯示 abc.txt 檔案中已替換的行
8$sed ‘1 s/tutorialspoint/tutorials/’ abc.txt替換 abc.txt 檔案中指定行的字串(在上面的命令中,它替換第一行(1)的字串)
9$ sed ‘1,3 s/tutorialspoint/tutorials/’ abc.txt替換 abc.txt 檔案中特定範圍內的字串(在上面的示例中,它替換從第一行到第三行的字串)
10$sed ‘/./,$!d’ abc.txt刪除 abc.txt 檔案中的所有空行
11$sed ‘3,$ d’ abc.txt刪除 abc.txt 檔案中的特定行(第三行)
12$sed ‘p’ abc.txt在 abc.txt 檔案中將每行列印兩次
13$ sed ‘i “Add a new line”‘ abc.txt在 abc.txt 檔案中每行的前面新增指定的行(“Add a new line”)
14$ sed ‘a “Add a new line”‘ abc.txt在 abc.txt 檔案中每行的後面新增指定的行(“Add a new line”)
15$sed -n ‘/tutorialspoint/ p’ abc.txt在 abc.txt 檔案的每一行中查詢指定的搜尋字串(tutorialspoint)

在本文中,我們學習瞭如何使用 sed Linux 命令進行文字和檔案處理。在我們的下一篇文章中,我們將介紹更多基於 Linux 的技巧和提示。請繼續關注!

更新於:2020年1月17日

488 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.