Linux之sed命令(包含MacOS使用方法)

Linux之sed命令

一、概述

Linux下的sed命令是一种流编辑器,用于在命令行中对文本进行处理,常见的操作如:添加、修改、删除、追加等。

当所用系统为MacOS时,直接使用sed会出现command a expects \ followed by text此类报错,处理方法如下:

解决方案1:sed命令改写 --> 添加一个空串

sed -i 's/apple/applewatch/g' /tmp/a.txt

改写为

sed -i '' 's/apple/applewatch/g' /tmp/a.txt
解决方案2:调整mac下的sed命令 --> 安装gnu-sed

执行:

shell 复制代码
brew install gnu-sed
alias sed=gsed

本人建议使用第二种方式解决,一劳永逸。

extra:在使用sed新增一行时会使用到\,macOS会把反斜杠解析为命令结束字符,后面不允许携带新字符,导致报错 extra characters after \ at the end of a command,只能通过把命令分割成两行内容。示例:

shell 复制代码
原命令:sed -i '$a new line' /tmp/a.txt
macOS下需要写成:
sed -i '' -e '$a\
new line' /tmp/a.txt

二、用法

以下介绍sed命令常用方法。

1、文件末尾追加一行

shell 复制代码
sed -i '$a <new_line>' <file_name>
示例:sed -i '$a this is a new line' /tmp/sed.txt

2、指定行后新增一行

shell 复制代码
sed -i '/<specific_line>/a\<new_line>' <file_name>
示例:sed -i '/an existing line/a\this is a new next line' /tmp/sed.txt

其中<specific_line>可以为模糊匹配,例如为line但有多行都包含line,此时会在所有包含line关键字的行后都新增一行。

此规则以下都适用。

3、指定行前新增一行

shell 复制代码
sed -i '/<specific_line>/i\<new_line>' <file_name>
示例:sed -i '/an existing line/i\this is a new upper line' /tmp/sed.txt

4、修改指定行

shell 复制代码
sed -i 's/<old_content>/<new_content>/g' <file_name>
示例:sed -i 's/magic_switch=0/magic_switch=1/g' /tmp/sed.txt

5、删除指定行

shell 复制代码
sed -i '/<specific_line>/d' <file_name>
示例:sed -i '/trash_line/d' /tmp/sed.txt
相关推荐
康熙38bdc2 分钟前
Linux 环境变量
linux·运维·服务器
GEEKVIP18 分钟前
手机使用技巧:8 个 Android 锁屏移除工具 [解锁 Android]
android·macos·ios·智能手机·电脑·手机·iphone
GEEKVIP29 分钟前
如何在 Windows 10 上恢复未保存/删除的 Word 文档
macos·ios·智能手机·电脑·word·笔记本电脑·iphone
hakesashou1 小时前
python如何比较字符串
linux·开发语言·python
奇客软件1 小时前
iPhone使用技巧:如何恢复变砖的 iPhone 或 iPad
数码相机·macos·ios·电脑·笔记本电脑·iphone·ipad
Ljubim.te1 小时前
Linux基于CentOS学习【进程状态】【进程优先级】【调度与切换】【进程挂起】【进程饥饿】
linux·学习·centos
cooldream20091 小时前
Linux性能调优技巧
linux
QMCY_jason2 小时前
Ubuntu 安装RUST
linux·ubuntu·rust
慕雪华年2 小时前
【WSL】wsl中ubuntu无法通过useradd添加用户
linux·ubuntu·elasticsearch
苦逼IT运维2 小时前
YUM 源与 APT 源的详解及使用指南
linux·运维·ubuntu·centos·devops