1. Replacing string

原文地址: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 
2
3
4

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  

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  

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  

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  

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  

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

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  

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  

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  

9. Deleting lines

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

1  
1  

10. Duplicating lines

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

1  

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

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 ' 

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  

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  

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   
1   

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  

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

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  
1  

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  

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  

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  

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  

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

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:

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


系ubuntu 下面打开终端输入:sudo apt-get install sendmail一般就安装完成噶啦跟住进入 /etc/mail/目录输入:m4 sendmail.mc > sendmail.cf意思系跟住.mc文件 生成 sendmial.cf文件输入呢个命令:ps aux | g
依家我有1个软件goagent目录(大家懂得) 放在/home/gateman/Programs/ 下 1. proxy.py 入面有1个 proxy.py 文件 放在/home/gateman/Programs/goagent/local/ 入面 2.breakwall.sh 我在 proxy.p
其实我想讲的是 cp -L关于-L参数的解释:-L, --dereference always follow symbolic links in SOURCE意思是如果复制目标是1个软链接,则复制链接的目标 不是链接本身做个例子: 例如 ~/tmp/fo1 入面有1个c.txt 文件 和 指向他的软
原地址:http://www.rjgc.net/control/content/content.php?nid=4418 1、将文件checkout到本地目录svn checkout path(path是服务器上的目录)例如:svn checkout svn://192.168.1.1/pro/do
chroot,即 change root directory (更改 root 目录)。在 linux 系统中,系统默认的目录结构都是以 `/`,即是以根 (root) 开始的。而在使用 chroot 之后,系统的目录结构将以指定的位置作为 `/` 位置。实例:用live CD ubuntu假设你的
简单解析下, stdin就是标准输入, stdout就是标准。举个例子, 在当前我要打包1个文件夹 /var/log/ 到当前目录下,并用zip压缩,那么我们可以分步执行#tar -cvf log.tar /var/log/#zip -r log.tar.zip log.tar#rm -rf log
转自:http://man.ddvip.com/linux/Mandrakelinuxref/process-priority.html系统中运行的每个进程都有一个优先级(亦称“nice 值”),其范围从 -20 (最高优先级)到 19 (最低优先级)。默认情况下,进程的优先级是 0 (“基本”调度
str="/home/gateman" if [ ${str:0:1} = "/" ]; then echo "yes'fi ${str:0:1} 中0表示从第几个字符开始,1表示截取多长
转自:http://kwokchivu.blog.51cto.com/1128937/694347 在RedHat系统下用usermod 命令可把某用户添加进多个附属组,默认情况下,一次性添加多个附属组可用以下方式来添加: usermod -G 附属组1,附属组2,...,附属组X 用户名 但在添加
有个文件 test.txt 内容如下:bash-3.00$ cat test.txt user user user_hiuser #注:呢行系空行T JGATEMANGATTTTTEMANGABBEMANAAABbash-3.00$下面介绍下常用的通配符 配合grep 命令:1. ".&q
linux系统为每1个文件都分配有i索引节点(inode),系统根据呢d节点从磁盘找出数据。 一般来讲,每1个文件名(包含全路径)实际上都链接住1个i索引节点。inode实际上系乜咧? 其实可以算系1个指向磁盘具体位置(柱面,扇区之类)的指针, 系统分析某个文件的inode,得出磁盘柱面,扇区等数据
grep 可以立即为筛选, 一般的用法系 grep + 要查询的字段 + 文件(或者内容 例如| 传递既内容)1.grep + 要查询的字段 + 文件gateman@GPC:~/shell/SQL_GSI$ grep OID a.sqlWHERE OID=@BuildNOWHERE OID INWH
原文转自:http://www.ibm.com/developerworks/cn/linux/l-cn-vimcolumn/index.html开始之前人类大脑对文字的处理是平面式的,所以我们浏览文章、查找资料或者重构代码,要么是横向读,要么是纵向读,要么使用搜索功能,将文字作为一个平面整体。而在
PS:偶很喜欢用scp这个命令来传输数据。scp命令跟cp命令类似,只不过cp命令是在同一台机器上用的,scp是在两台机器上复制传输数据的命令。scp实质相当于利用SSH协议来传输数据的cp命令。 用法举例: 1、复制远程服务器的文件到本地: scp -P888 root@120.18.50.33:
打开终端,进入/bin/ls 一下会见到 bash sh 呢两个文件。其实距地系两个唔同既shell 解析器。如果在脚本a.sh 开头写入#!/bin/sh那么执行./a.sh 时候 就相当于 sh a.sh同理 开头写入#!/bin/bash执行./a.sh 时候 就相当于 bash a.sh如果
find查找文件的时候排除某个或几个文件或目录转自:http://www.cnblogs.com/starspace/archive/2008/10/20/1315380.html比如要在/usr/sam目录下查找不在dir1子目录之内的所有文件find /usr/sam -path "/
假设有变量 var=http://www.google.com/test.htm一 # 号截取,删除左边字符,保留右边字符。echo ${var#*//}其中 var 是变量名,# 号是运算符,*// 表示从左边开始删除第一个 // 号及左边的所有字符即删除 http://结果是 :www.goog
转自: http://edyfox.codecarver.org/html/_vimrc_for_beginners.htmlVIM 中可供用户定制的选项非常非常多,作为初学者,我们没有必要了解这么多东西。下面,滇狐简单列出了一些最常用的配置项,大家可以根据自己的需要将这些内容添加到自己的 .vim
转自:http://www.einit.com/user1/11/archives/2006/3603.htmlUnix/Linux下一般想让某个程序在后台运行,很多都是使用 & 在程序结尾来让程序自动运行。比如我们要运行mysql在后台: /usr/local/mysql/bin/mysq
首先, mount是类unix系统, 挂载设备到1个文件夹的操作命令, 注意系设备阿正常来讲,mount 是不能挂在文件夹到文件夹的。例如, 在我的~/tmp/ 目录中有两个文件夹fo1 fo2其中fo1 中有3个文件a.txt b.txt c.txt fo2 有4个 e.txt d.txt e.t