Linux文本处理–sed命令编辑器

时间:2021-03-14 11:03:28

sed编辑器–Stream editor(流编辑器),相对于交互式编辑器如vim无法进行人工交互,需要根据在编辑器处理数据之前事先提供的规则集编辑数据流。

sed编辑器可以根据输入命令行的命令或者存储在文本文件中的命令处理数据。每次从输入读取一行数据,将数据与编辑器提供的命令进行匹配,修改数据流中的数据,然后将心数据输入到stdout。处理完数据流中所有的数据行之后,流编辑器停止。 正是由于按顺序逐行应用命令,因而使得sed编辑器比交互式编辑器要快速。
Usage: sed [OPTION]… {script-only-if-no-other-script} [input-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 extension supplied)
  -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
      –help     display this help and exit
      –version  output version information and exit
If no -e, –expression, -f, or –file option is given, then the first
non-option argument is taken as the sed script to interpret.  All
remaining arguments are names of input files; if no input files are
specified, then the standard input is read.

1. 直接在命令中定义编辑器命令

echo “This is a test” | sed ‘s/test/big test/’

输出This is a big test 上面的例子只是编辑了一行数据,下面看编辑文本文件的例子。 文本文件的名称为data

sed ‘s/a/an/’ data

将文本文件中的a替换成an 2. 在命令行使用多个编辑器命令 如果使用多个编辑器命令,则需要使用-e选项。

sed -e ‘s/This/That/; s/a/an/’ data

3. 从文件读取编辑器命令

如果命令选项规则比较多,可以将这些规则放到文件中,并且使用-f选项。

sed -f script data