和大多数人一样,都觉得sed和awk非常有用,会一点但是自己确很难运用。今天花了点时间把这两个工具重新学习了一遍,希望能够灵活运用。
sed
A Stream EDitor is used to perform basic transformations on text read from a file or a pipe. The result is sent to standard output. The syntax for the sed command has no output file specification,
but results can be saved to a file using output redirection. The editor does not modify the original input.
简单的说,就是能够对一些文本进行处理成新的文本,每次一行为单位进行输入和输入。
常见的命令就是:
1,替换
sed ‘s/oldtext/newtext/g‘ INPUTFILE //将每行所有的oldtext替换成newtext
sed ‘s/^/----/‘ INPUTFILE //将每行开头替换成-----,^表示每行开头
sed ‘s/$/--->/‘ INPUTFILE
//将每行结尾替换成--->,$表示每行开头
2,搜索匹配
sed -n ‘/text/p‘ INPUTFILE
//查找text的行
awk
The basic function of awk is to search files for lines or other text units containing one or more patterns. When a line matches one of the patterns, special actions
are performed on that line.
简单的说,就是基于每行或者行中的列,对行数据进行加工。
常用的方法:
1,替换分隔符
awk ‘BEGIN{FS=":"}‘
2,打印特定的列
awk ‘{print "The second column is :"$2}‘
3,变量定义
awk ‘BEGIN{total=0} {total+=$2;print total}‘