Chinaunix首页 | 论坛 | 博客
  • 博客访问: 45263
  • 博文数量: 14
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 150
  • 用 户 组: 普通用户
  • 注册时间: 2015-11-16 18:43
文章分类

全部博文(14)

文章存档

2016年(6)

2015年(8)

我的朋友

分类: LINUX

2015-11-21 18:23:41

写在前头:
文章是作者通过阅读《sed&awk》中一些所悟所感,希望每天都能够有所感有所进步。

(1)脚本需求:
对输入文本的每一行指定位置插入指定字段

(2)脚本:
awk -v filename=$1 '
function insert(STRING, POS, INS) {
        before=substr(STRING, 1, POS)
        after=substr(STRING, (POS+1))
        return before INS after
}
BEGIN{
        printf ("input insert location and insert segment: ")
}
FILENAME == filename {
        entry[NR]=$0
        next    ###################最后一个行时next命令读入空行导致NR为3,原文本NR为2################
}
{
print NR   #####测试NR值#####
for ( i=1;i<NR;i++){            ####因为NR值为3所以此处为小于,没有等于号#####
        print insert(entry[i], $1, $2 )
}
exit
}' $1 -


(3)执行:
[root@czw unit9]#cat testfile
123
123

[root@czw unit9]#./awkscript testfile
input insert location and insert segment: 1 gg # 1 gg为键入内容,指定插入位置和内容
3     #为此测试NR值,发现为3,即最后一个行时next命令读入空行导致NR为3,原文本NR为2
1gg23
1gg23

测试NR值:
[root@czw unit9]# awk '{print NR}' testfile2_match 
1
2

(4)总结
next命令会导致NR值改变,接下来脚本应用NR值需要注意

阅读(944) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~