笔记:awk(二) 不指定

root , 2007/08/21 22:01 , SHELL , 评论(0) , 阅读(6364) , Via 本站原创 | |
内置的字符窜函数
gsub(r,s)                                                                   在整个$0中用s替代r
gsub(r,s,t)                                                                 在整个t中用s替代r
index(s,t)                                                                   返回s中字符串t的第一位置
length(s)                                                                    返回s长度
match(s,r)                                                                  测试s中是否包含匹配r的字符串
split(s,a,fs)                                                                在fs上将s分成序列a
sub(s, )                                                                      用$0中最左边也是最长的字符串替代
subtr(s,p)                                                                  返回字符串s中从p开始的后缀部分
substr(s,p,n)                                                             返回字符串s中从p开始长度为n的后缀部分
1.gsub
awk 'gsub(/4842/,4899) {print $0}' input-file             #/4842/为目标模式   4899为替换模式
awk 'gsub(/0/,2) {print $0}' /etc/fstab
awk '{print gsub(/0/,2) $0}' /etc/fstab                        
2.index查询字符串s中t出现的第一位置
awk 'BEGIN {print index("root","o")}'
awk -F: '$1=="root" {print index($1,"o")" "$1}' /etc/passwd
awk -F: '{print index($1,"o") $1}' /etc/passwd
3.length
awk -F: '{print length($1)} /etc/passwd'
awk 'BEGIN {$1="root" print length($1)'
4.match (在ANCD中查找C的位置)
awk 'BEGIN {print match("ANCD" ,/C/)}'
5.split
返回字符串数组元素个数
awk 'BEGIN {print split("123#456#789", myarray, "#")}'
6.sub 只能替换指定域的第一个0
awk '{print sub(/0/,"2",$1)' /etc/fstab
awk '{print sub(/0/,"2",$6)' /etc/fstab
7.substr 按照起始位置及长度返回字符串的一部分
awk 'BEGIN {print substr("Pavel.Nedved",7,3)}'
awk 'BEGIN {print substr("Pavel.Nedved",7)}'
awk -F: '{print substr($1,3)" " $1)}' /etc/passwd

字符串屏蔽序列
\b                                                                退格键
\f                                                                 走纸换页
\n                                                                新行
\r                                                                 回车
\t                                                                 tab
\c                                                                任意其他特殊字符
\ddd                                                            八进制
很简单的例子
awk -F: '{print $1,"\b"$2,"\t"$3} /etc/passwd
Tags:
发表评论

昵称

网址

电邮

打开HTML 打开UBB 打开表情 隐藏 记住我 [登入] [注册]