原文地址:https://www.systemcodegeeks.com/shell-scripting/bash/linux-sed-examples/?ref=dzone

Sed is basically a stream editor used for modifying files in unix or linux. It provides a nifty way to perform operations on files which can be passed around through pipes. Most people never learn its real power, they just simply use sed to replace text. You can do many things apart from replacing text with sed.

As mentioned earlier, sed is an editor that allows us to use pattern matching to search and replace within a file, or an input stream. This works by using Regular Expressions. By default, the results of any edits we make to a source file, or input stream, will be sent to STDOUT, the standard output. The original file will be unaffected by the edits.

Also the sed command can be incredibly useful when bootstrapping a new server, or machine, as it can easily be scripted. A common use case for sed is to script the editing of configuration files on a new server instance to facilitate the further setup of the needed environment for that machine.

In this article I will describe the capabilities of sed with examples. Consider the below file as input to our examples:

1 >cat example.txt
2 I want to learn java. Learn java. Learn java
3 java is the best
4 java forever

1. Replacing string

Sed command is mostly used to replace the text in a file. The below sed command replaces the word “java” with “guava” in the file only for the first occurrence in each line:

1 >sed 's/java/guava/' example.txt

Here the “s” specifies the substitution operation. The “/” are delimiters. The “java” is the search pattern and the “guava” is the replacement string.

By default, the sed command replaces the first occurrence of the pattern in each line and it won’t replace next occurences.

2. Replacing the nth occurrence of a pattern in a line

Use the /1, /2 etc flags to replace the first, second occurrence of a pattern in a line. The below command replaces the second occurrence of the word “java” with “guava” in a line:

1 >sed 's/java/guava/2' example.txt

3. Replacing all the occurrences of a pattern in a line

The substitute flag /g (global replacement) specifies the sed command to replace all the occurrences of the string in the line:

1 >sed 's/java/guava/g' example.txt

4. Replacing from nth occurrence to all occurrences in a line

Use the combination of /1, /2, /n and /g to replace all the patterns from the nth occurrence of a pattern in a line. The following sed command replaces from the second occurrence until the nth of the word “java” with the word “guava” in a line:

1 >sed 's/java/guava/2g' example.txt

5. Duplicating the replaced line with /p flag

The /p print flag prints the replaced line twice on the terminal. If a line does not have the search pattern and is not replaced, then the /p prints that line only once.

1 >sed 's/java/guava/p' example.txt

The below image illustrates the execution of the first 5 sed commands:

Sed Examples 1-5

6. Replacing string on a specific line number

You can restrict the sed command to replace the string on a specific line number. The below sed command replaces the string “java” only on the second line:

1 >sed '2 s/java/guava/' example.txt

7. Replacing string on a range of lines

You can specify a range of line numbers to the sed command for replacing a string. Here the sed command replaces the lines with range from 1 to 3. You may use the $ operator to indicate the last line in the file:

1 >sed '1,$ s/java/guava/' example.txt

8. Replacing on a line which matches a pattern

You can specify a pattern to the sed command to match in a line. If the pattern match occurs, then the sed command looks only for the string to be replaced and if it finds it, then it replaces the string. Here the sed command first looks for the lines which have the pattern “java” and then replaces the word “java” with “guava”.

1 >sed '/java/ s/java/guava/' example.txt

9. Deleting lines

You can delete the lines of a file by specifying the line number or a range of numbers:

1 >sed '2 d' example.txt
1 >sed '1,$ d' example.txt

10. Duplicating lines

You can use the sed command to print each line of a file two times:

1 >sed 'p' example.txt

The below image illustrates the execution of the previous 5 sed commands:

Sed Examples 6-10

11. Changing the slash (/) delimiter

You can use any delimiter other than the slash. As an example if you want to change the web url to another url, using too many backslashes makes the sed command look awkward. In this case we can change the delimiter to another character as shown in the below example:

1 >sed 's_http://_www_' example.txt

12. Using & as the matched string

There might be cases where you want to search for the pattern and replace that pattern by adding some extra characters to it. In such cases & comes in handy. The & represents the matched string:

1 >sed 's/java/{&}/' example.txt

13. Using \1,\2 and so on to \9

The first pair of parenthesis specified in the pattern represents the \1, the second represents the \2 and so on. The \1,\2 can be used in the replacement string to make changes to the source string. As an example, if you want to replace the word “java” in a line with twice as the word like “javajava” use the sed command as below:

1 >sed 's/\(java\)/\1\1/' example.txt

14. Running multiple sed commands

You can run multiple sed commands by piping the output of one sed command as input to another sed command. Sed provides also an -e option to run multiple sed commands in a single sed command:

1 >sed 's/java/guava/' example.txt | sed 's/guava/python/'
1 >sed -e 's/java/guava/' -e 's/guava/python/' example.txt

15. Printing only the replaced lines

Use the -n option along with the /p print flag to display only the replaced lines. Here the -n option suppresses the duplicate rows generated by the /p flag and prints the replaced lines only one time:

1 >sed -n 's/java/guava/p' example.txt

The below image illustrates the execution of the previous 5 sed commands:

Sed Examples 11-15

16. Using sed as grep

You can make sed command to work as similar to grep command. Here the sed command looks for the pattern “java” in each line of a file and prints those lines that have the pattern:

1 >grep 'java' example.txt
1 >sed -n '/java/ p' example.txt

17. Adding a line after a match is found.

The sed command can add a new line after a pattern match is found. The “a” command to sed tells it to add a new line after a match is found:

1 >sed '/java/ a "Add a new line"' example.txt

18. Adding a line before a match

The sed command can add a new line before a pattern match is found. The “i” command to sed tells it to add a new line before a match is found:

1 >sed '/java/ i "New line"' example.txt

19. Changing a line

The sed command can be used to replace an entire line with a new line if a match is found. The “c” command to sed tells it to change the line.

1 >sed '/java/ c "Change line"' example.txt

20. Transforming like tr command

The sed command can be used to convert the lower case letters to upper case letters by using the transform “y” option. In the below example the sed command transforms the alphabets “av” into their uppercase format “AV”

1 >sed 'y/av/AV/' example.txt

The below image illustrates the execution of the last 5 sed commands:

Sed Examples 16-20

Man sed

We tried to present some basic examples of using the sed command. Of course you may always use the man command to find the full functionality of the sed command:

 >man sed

Linux sed Examples--转载的更多相关文章

  1. linux 命令总结(转载)

    linux 命令总结(转载) 1. 永久更改ip ifconfig eth0 新ip 然后编辑/etc/sysconfig/network-scripts/ifcfg-eth0,修改ip 2.从Lin ...

  2. Linux sed 替换第一次出现的字符串

    /********************************************************************************* * Linux sed 替换第一次 ...

  3. linux sed命令参数及用法详解

    linux sed命令参数及用法详解 http://blog.csdn.net/namecyf/article/details/7336308 1. Sed简介 sed 是一种在线编辑器,它一次处理一 ...

  4. linux sed 批量替换多个文件中的字符

    格式: sed -i "s/查找字段/替换字段/g" `grep 查找字段 -rl 路径` linux sed 批量替换多个文件中的字符串 sed -i "s/oldst ...

  5. Linux计划任务(转载)

    Linux计划任务(转载) Linux的计划任务是系统管理方面的一个重要内容,是系统自动完成工作的一种实现方式,正因为有了计划任务,我们才可以完全实现系统管理的脚本化和自动化. 关于计划任务,Linu ...

  6. [转帖]linux sed命令

    linux sed命令就是这么简单 https://www.cnblogs.com/wangqiguo/p/6718512.html 用到的最多的就是一个sed -i 's/nn/mm/' 的命令了. ...

  7. 理解linux sed命令

    理解linux sed命令(2010-02-27 18:21:20) 标签:linuxshellsed替换 分类:革命本钱 1. Sed简介sed是一种在线编辑器,它一次处理一行内容.处理时,把当 前 ...

  8. learn Linux sed command

    learn Linux sed command 一.参考文档: . sed命令详解 http://qifuguang.me/2015/09/21/sed%E5%91%BD%E4%BB%A4%E8%AF ...

  9. 【转】linux sed命令

    转自:linux sed命令就是这么简单 参考:Linux三大剑客之sed:https://blog.csdn.net/solaraceboy/article/details/79272344 阅读目 ...

随机推荐

  1. SQL Server 2008 删除数据库帐号失败问题

    SQL Server 2008 中单独为一个项目建立了一个账号zdhsa,结果发现无法删除. 问题:删除zdhsa失败. 解决:首先从"安全性"-"架构"中删除 ...

  2. jQuery 之父:每天写代码

    去年秋天我的支线代码项目 遇到了一些问题,项目进展不足,而且我没法找到一个完成更多代码的方法(在不影响我在Khan Academy方面的工作的前提下). 我主要在周末进行我的支线,当然有时候也在晚上进 ...

  3. HDU 1711 Number Sequence (KMP)

    白书说这个是MP,没有对f 数组优化过,所以说KMP有点不准确 #include <stdio.h> int a,b; int T[1000010],P[10010];//从0开始存 in ...

  4. EWM 强大的数据修复功能

    在上了EWM系统后,运行一段时间可能因为不正确的操作,系统意外情况数据不一致的问题,交货单行项目状态不致,等等报不一致的情况,EWM的自检功能比较强. 下面介绍一种数据不致的修复工具之一,tx: /S ...

  5. Linux下面使用rpm命令

    RPM是RedHat Package Manager(RedHat软件包管理工具)类似Windows里面的“添加/删除程序” rpm 执行安装包二进制包(Binary)以及源代码包(Source)两种 ...

  6. HTTP基本认证(Basic Authentication)的JAVA示例

    大家在登录网站的时候,大部分时候是通过一个表单提交登录信息.但是有时候浏览器会弹出一个登录验证的对话框,如下图,这就是使用HTTP基本认证.下面来看看一看这个认证的工作过程:第一步:  客户端发送ht ...

  7. (ETW) Event Trace for Windows 提高 (含pdf下载)

    内容提纲 • 托管代码与非托管代码介绍 • 不安全代码介绍 • 用户模式与内核模式 • ETW执行流程分析 • 日志分析工具介绍:PerfView.exe   ETW与非托管代码 • ETW依赖的So ...

  8. 2014中国软件开发者调查(二):Java、.NET、Web、云计算特点

    继上周五放出第一篇中国软件开发者调查报告后,很多初学者和开发者翘首以盼第二篇.第三篇报告--希望这些调查报告能够给他们带来指导,解决他们的疑惑.确定他们的学习和使用信心.经过笔者在周末的努力,内容更加 ...

  9. AWVS漏洞测试-03节-添加扫描项目

    http://localhost:9660 我们要扫描这个页面 点击左上角的New Scan,在Scan Single哪里输入要扫描的网站地址,可以是本地地址 然后选择下一步 Next 这里我们可以配 ...

  10. Hadoop 2.7.1 源代码目录结构分析

    采用的源代码是2.7.1的,从这个网站下可以找到2.7.1的代码:https://git1-us-west.apache.org/ ,使用gitclone出来,然后git checkout到2.7.1 ...