0%

文件处理三剑客- -sed

学习 sed

简介

语法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
sed --help
Usage: sed [OPTION]... {script-only-if-no-other-script} [input-file]...

-n, --quiet, --silent
suppress automatic printing of pattern space
--debug
annotate program execution
-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)
-b, --binary
open files in binary mode (CR+LFs are not processed specially)
-l N, --line-length=N
specify the desired line-wrap length for the `l' command
--posix
disable all GNU extensions.
-E, -r, --regexp-extended
use extended regular expressions in the script
(for portability use POSIX -E).
-s, --separate
consider files as separate rather than as a single,
continuous long stream.
--sandbox
operate in sandbox mode (disable e/r/w commands).
-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
--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.

GNU sed home page: <https://www.gnu.org/software/sed/>.
General help using GNU software: <https://www.gnu.org/gethelp/>.
E-mail bug reports to: <bug-sed@gnu.org>.

添加内容

1
2
3
4
5
6
7
8
9
# 指定行插入文本信息
# file.txt 为添加的内容信息
sed -i '4r file.txt' change_file.txt

# 在文本行后添加信息
sed -i 's/match_string/&add_string/' change_file.txt

# 在匹配信息的后一行添加带空格的字符串
sed -i '/match_info/i\ add_string' change_file.txt

替换内容

1
2
# 根据匹配的信息替换
sed -i '/match_info/s/match_string/change_string/g' change_file.txt

删除内容

1
2
# 删除文本中2到5行的内容
sed -i '2,5d' change_file.txt

多点编辑

1
2
# 替换文本中的多个内容
echo "{test_1=1, test_2=2}" | sed -e 's/{//' -e 's/}//' -e 's/,//g'