linux sed 常用方法

基础用法:
Usage: sed [OPTION]... {script-only-if-no-other-script} [input-file]..

sed [-nefri] 'command' [file ...]

  -n, --quiet, --silent  安静模式
                 suppress automatic printing of pattern space
  -e script, --expression=script 添加命令执行(可多个命令)
                 add the script to the commands to be executed
  -f script-file, --file=script-file  指定命令文件执行
                 add the contents of script-file to the commands to be executed
  --follow-symlinks
                 follow symlinks when processing in place
  -i[SUFFIX], --in-place[=SUFFIX] 直接便捷源文本
                 edit files in place (makes backup if SUFFIX supplied)
  -c, --copy
                 use copy instead of rename when shuffling files in -i mode
  -b, --binary
                 does nothing; for compatibility with WIN32/CYGWIN/MSDOS/EMX (
                 open files in binary mode (CR+LFs are not treated specially))
  -l N, --line-length=N
                 specify the desired line-wrap length for the `l' command
  --posix
                 disable all GNU extensions.
  -r, --regexp-extended
                 use extended regular expressions in the script.
  -s, --separate
                 consider files as separate rather than as a single continuous
                 long stream.
  -u, --unbuffered
                 load minimal amounts of data from the input files and flush
                 the output buffers more often
  -z, --null-data
                 separate lines by NUL characters

常用命令

  • a 新增
  • d 删除
  • s 替换
  • p 打印

删除文件的内容
通过 d 参数加匹配规则,我们可以方便的删除文件中的内容。

sed '3d' fileName.txt #删除第3行,标准输出
sed -i '3d' fileName.txt #删除源文件第3行

# 删除最后一行
sed '$d' fileName.txt

# 删除7-9行
sed '7,9d' fileName.txt

# 删除所有空行
sed '/^$/d' fileName.txt
sed '/./!d' fileName.txt

# 删除匹配到字符串的行
sed '/awk/d' fileName.txt

# 删除两个匹配之间所有的行
sed '/patternA/,/patternB/d' fileName.txt

# 删除匹配的行到第 n(5) 行之间的内容,同理也可以反过来,删除某一行到匹配行之间的内容
sed '/pattern/,5d' fileName.txt

# 删除符合多个条件的行
sed '/patternA/d;/patternB/d' fileName.txt

替换

sed 's/src/dst/' filename

人生还有意义。那一定是还在找存在的理由
原文地址:https://www.cnblogs.com/shiqi17/p/15343976.html