sed 实现cat -n

#!/usr/bin/sed -nf
    
     # Prime the pump on the first line
  pattern space中读入一行
     x
  首先是交换指令,将hold space和pattern space的内容互换
     /^$/ s/^.*$/1/
     判断pattern space是否为空,如果刚开始运行则前面hold space为空的,否则hold space保存的是前一次的行号。
  为空则将行号设置为1
 
     # Add the correct line number before the pattern
     G
  将hold space中的文件行添加到pattern space中,此时pattern space为:
  n                    行号
  XXXXXXXX             行内容
 
     h                    将pattern space的内容复制到hold space
    
     # Format it and print it
     s/^/      /
  行号前面添加空格
     s/^ *\(......\)\n/\1  /p
  去掉换行符,同时前面行号与空格共保留6个字符,并显示出来:
 
        n  XXXXXXXXXX
 
    
     # Get the line number from hold space; add a zero
     # if we're going to add a digit on the next line
     g
  将hold space中的内容复制到pattern space中
     s/\n.*$//
  去掉行号后面的所有内容
     /^9*$/ s/^/0/
     如果是行号全为9的话说明需要进位了,那么先在前面添加0,(s/^/0/是添加0,而不是替换)
 
     # separate changing/unchanged digits with an x
     s/.9*$/x&/
  将需要修改的部分用x分隔开,如12 1x2  09  x09  119 1x19 
    
     # keep changing digits in hold space
     h           将pattern space的分隔好的数字复制到hold space
     s/^.*x//    去掉x前面不需要修改的部分,包括x
     y/0123456789/1234567890/  进行修改
     x                      互换
    
     # keep unchanged digits in pattern space
     s/x.*$//            去掉x以及后面需要修改的数字
    
     # compose the new number, remove the newline implicitly added by G
     G                   添加上修改好的数字
     s/\n//              去掉换行符
     h                   保存到hold space中
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值