阅读量:119
sed 是一个流编辑器,用于对输入流(文件或管道)执行基本的文本转换
替换文本:
sed 's/要查找的文本/替换的文本/' input_file > output_file
例如,将文件 example.log 中的所有 “apple” 替换为 “orange”:
sed 's/apple/orange/' example.log > new_example.log
删除包含特定文本的行:
sed '/要查找的文本/d' input_file > output_file
例如,删除 example.log 中包含 “error” 的所有行:
sed '/error/d' example.log > new_example.log
在匹配特定文本的行之后插入文本:
sed '/要查找的文本/a 要插入的文本' input_file > output_file
例如,在 example.log 中包含 “warning” 的行之后插入一行空行:
sed '/warning/a\' example.log > new_example.log
在匹配特定文本的行之前插入文本:
sed '/要查找的文本/i 要插入的文本' input_file > output_file
例如,在 example.log 中包含 “info” 的行之前插入一行空行:
sed '/info/i\' example.log > new_example.log
修改匹配特定文本的行:
sed '/要查找的文本/c 要替换的文本' input_file > output_file
例如,将 example.log 中包含 “old” 的行替换为 “new”:
sed '/old/c new' example.log > new_example.log
注意:以上命令中的 input_file 是要编辑的日志文件,output_file 是编辑后的输出文件。如果要直接修改原始文件,请使用 -i 选项:
sed -i 's/要查找的文本/替换的文本/' input_file
例如,将 example.log 中的所有 “apple” 替换为 “orange” 并直接修改原始文件:
sed -i 's/apple/orange/' example.log