shellsed命令详解

发布时间:2023-05-19

一、sed命令简介

sed是一种基于行的编辑器,专门用于从文件中选择行文本,对其进行转换或删除。sed命令对于Unix和Linux用户来说是必须掌握的技能之一。

二、sed命令参数解析

命令格式:sed [选项] 'command' filename 选项:

  • -n:禁止默认输出,只能与p命令使用
  • -e:命令选项后面可以接多个sed命令
  • -f:指定从文件中读取sed命令 command:是sed命令。例如:p、d、s/.old/.new/g等命令。 filename:文件名,在命令中可以使用多个文件名。

三、shell中常见的sed命令

1、shellsed命令详解

shellsed是一个非交互式编辑器,它允许我们将sed命令与shell脚本结合起来对文件进行操作。下面是一个示例:

#!/bin/bash
echo "The original file content is:"
cat demo.txt
echo "The edited file content is:"
sed 's/is/are/g' demo.txt

以上脚本将文件demo.txt中的is替换为are,并输出修改后的内容给我们查看。

2、shellsed删除命令详解

删除文件指定字符串命令格式:sed '/word/d' filename,下面是一个示例:

#!/bin/bash
echo "The original file content is:"
cat demo.txt
echo "The edited file content is:"
sed '/apple/d' demo.txt

以上脚本将文件demo.txt中的所有含有apple的行都删除并输出修改后的内容给我们查看。

3、shellsed选取命令详解

选取文件指定字符串命令格式:sed -n '/word/p' filename,下面是一个示例:

#!/bin/bash
echo "Only show lines containing apple:"
sed -n '/apple/p' demo.txt

以上脚本将文件demo.txt中所有含apple字符串的行选取并输出。

4、shellsed替换命令详解

替换文件指定字符串命令格式:sed 's/old/new/g' filename,下面是一个示例:

#!/bin/bash
echo "The original file content is:"
cat demo.txt
echo "The edited file content is:"
sed 's/George/Tom/g' demo.txt

以上脚本将demo.txt文件中所有的George替换为Tom,并输出修改后的内容给我们查看。

5、shellsed追加命令详解

在指定行后追加文字命令格式:sed '/word/a 新增文字' filename,下面是一个示例:

#!/bin/bash
echo "The original file content is:"
cat demo.txt
echo "The edited file content is:"
sed '/apple/a Oranges' demo.txt

以上脚本将文件demo.txt中所有含apple的行后都追加Oranges,输出修改后的内容给我们查看。

6、shellsed插入命令详解

列出指定行并在该行前插入文字命令格式:sed -i '/apple/i 新增文字' filename,下面是一个示例:

#!/bin/bash
echo "The original file content is:"
cat demo.txt
echo "The edited file content is:"
sed -i '/apple/i Oranges' demo.txt

以上脚本将文件demo.txt中所有含apple的行前都插入Oranges,输出修改后的内容给我们查看。

总结

shellsed命令是Unix和Linux用户必须掌握的技能之一,它具有非常丰富的用途和远超我们上文所介绍的用法。