sed命令是我们在linu类系统中非常重要的一个命令, 但是在macos下面默认是没有sed命令的, 不过我们可以通过brew install gnu-sed ( 或者通过 sudo port install gsed )这个软件包来获得这个命令
GNU sed 命令安装
下面2种方式,选择一种安装即可
bash
# brew安装
brew install gnu-sed
# macport 安装
sudo port install gsed
macos里面在brew install gnu-sed安装后的默认命令是 gsed, 如果我们希望使用sed命令需要在配置文件 ~/.bash_profile 里面增加命令别名:
alias sed="gsed "
或者在 ~/.bash_profile 中增加sed命令的路径到path
export PATH="/usr/local/opt/gnu-sed/libexec/gnubin:$PATH"
GNU sed 命令使用示例
sed(流编辑器)是一个非交互式命令行文本编辑器。
bash
# 示例:删除文件中的第4行
$ sed '4d' input.txt > output.txt
#示例:将第10-20行中每次出现的"hello"替换为"world"
$ sed '10,20s/hello/world/' input.txt > output.txt
sed通常用于过滤文本,即它接受文本输入,对其执行一些操作(或一组操作),并输出修改后的文本。sed通常用于使用模式匹配或替换文件中字符串的多次出现来提取文件的一部分。
参考 gnu sed官方使用手册
- 1 Introduction
- 2 Running sed
- 3 sed scripts
- 4 Addresses: selecting lines
- 5 Regular Expressions: selecting text
- 5.1 Overview of regular expression in sed
- 5.2 Basic (BRE) and extended (ERE) regular expression
- 5.3 Overview of basic regular expression syntax
- 5.4 Overview of extended regular expression syntax
- 5.5 Character Classes and Bracket Expressions
- 5.6 regular expression extensions
- 5.7 Back-references and Subexpressions
- 5.8 Escape Sequences - specifying special characters
- 5.9 Multibyte characters and Locale Considerations
- 6 Advanced sed: cycles and buffers
- 7 Some Sample Scripts
- 7.1 Joining lines
- 7.2 Centering Lines
- 7.3 Increment a Number
- 7.4 Rename Files to Lower Case
- 7.5 Print bash Environment
- 7.6 Reverse Characters of Lines
- 7.7 Text search across multiple lines
- 7.8 Line length adjustment
- 7.9 Reverse Lines of Files
- 7.10 Numbering Lines
- 7.11 Numbering Non-blank Lines
- 7.12 Counting Characters
- 7.13 Counting Words
- 7.14 Counting Lines
- 7.15 Printing the First Lines
- 7.16 Printing the Last Lines
- 7.17 Make Duplicate Lines Unique
- 7.18 Print Duplicated Lines of Input
- 7.19 Remove All Duplicated Lines
- 7.20 Squeezing Blank Lines
- 8 GNU sed's Limitations and Non-limitations
- 9 Other Resources for Learning About sed
- 10 Reporting Bugs
- Appendix A GNU Free Documentation License
- Concept Index
- Command and Option Index