Linux SED命令

时间:2020-02-23 14:40:26  来源:igfitidea点击:

sed或者streamditor命令是在终端工作时任何Linux用户的必读命令之一。

SED命令可在文本文件中执行各种任务,例如更新,删除,搜索和插入文本。
其中一个强大的功能是使用正则表达式的支持。
此外,它允许我们编辑文件而无需打开文件。

在本教程中,除了一些有用的提示和技巧之外,我们将向我们展示SED命令的不同用途,这些技巧应该在日常Linux中使用。
对于本教程,我们正在使用Ubuntu作为我们的Linux机器,但我们可以使用以下教程在任何Linux发行版上。

首先,让我们确保系统是使用以下命令的最新命令:

sudo apt update
sudo apt upgrade

SED命令用途与例子

syntax

sed OPTIONS... [SCRIPT] [INPUTFILE...]

在开始命令之前,让我们确保已在计算机上安装SED。

sed --version

让我们创建一个新的文本文件,我们将用于测试我们的示例。

vi theitroad_sed

这是文件中的文本,以便我们可以使用它来测试自己。

1. hi theree
2. Sed or Stream Editor command is considered one of the Linux well-known commands that you must know.
3. Using the sed command will help you in performing various tasks on a text file like updating, deleting, searching and inserting text.
4. One of the sed important features is that it supports using regular expressions.
5. Also, the sed command can be used to edit files without even opening it.
6. In this guide, we will show you different uses of sed command besides some useful tips and tricks that will help you in your daily Linux use.
7. For this tutorial, we are using Ubuntu as our Linux machine but you can use the below sed commands in any Linux distribution.

示例1.用"Seeeeeeed"替换"SED"字的所有发生。
请注意,其区分大小写。

sed 's/sed/SEEEEEEED/g' theitroad_sed

示例2.除了第四行中的"SED"字除以"SEDEEEED"替换"SED"字。

sed '4!s/sed/SEEEEEEED/' theitroad_sed

示例3.在每行开头添加空格,然后将输出重定向到新文本文件。

sed 's/^//' theitroad_sed > new_theitroad_sed

为新文件添加空格并将输出重定向输出。

示例4.预览"SED"Word和"表达式"字之间的所有文本。

sed -n '/Sed/,/expressions/p' theitroad_sed

示例5.预览2nd和第5行之间的所有文本。

sed -n '2,5p' theitroad_sed

示例6.预览除2nd和第5行之间的文本之外的所有文本。

sed '2,5d' theitroad_sed

示例7.现在文件中的所有空格。

sed G theitroad_sed

示例8.从文件中删除最后一行。

sed '$d' theitroad_sed

示例9.在找不到"Unix"的行中将"Linux"替换成"Ubuntu"。

sed '/Unix/!s/Linux/Ubuntu/' theitroad_sed

示例10.删除具有"常规"字之间的第二行和行之间的所有文本。

sed '2, /regular /d' theitroad_sed

示例11.从每行的开头删除所有空格。

sed 's/^[ ^t]*//' new_theitroad_sed

示例12.从每行的末尾删除所有空格。

sed 's/[ ^t]*$//' new_theitroad_sed

示例13.从每行的开头和末尾删除所有空格。

sed 's/^[ ^t]*//;s/[ ^]*$//' new_theitroad_sed

示例14.替换仅在一行中的第1实例中找到的字符串。

sed 's/2/2222/' theitroad_sed

示例15.替换仅在3号实例中找到的字符串。

sed 's/e/eeeeeee/' theitroad_sed

示例16.替换在行中的所有实例中找到的字符串。

sed 's/e/eeeeeee/g' theitroad_sed

示例17.只有找到某个单词,替换字符串。

sed '/sed/s/a/aaaa/g' theitroad_sed