zoukankan      html  css  js  c++  java
  • linux shell实现将匹配字符行的最后一个字符替换为指定字符

    1、测试数据

    root@PC1:/home/test/test# ls
    test.txt
    root@PC1:/home/test/test# cat test.txt  ## 实现将每行最后一个e替换为xxx
    e r e y e u e
    e e g e 3 h r
    1 3 e g e y e
    e s e e e e e

    2、while 循环 + sed实现

    root@PC1:/home/test/test# ls
    test.txt
    root@PC1:/home/test/test# cat test.txt
    e r e y e u e
    e e g e 3 h r
    1 3 e g e y e
    e s e e e e e
    root@PC1:/home/test/test# awk '{print NR,gsub(/e/,"&")}' test.txt  ## 统计每行e的数目,并加行号
    1 4
    2 3
    3 3
    4 6
    root@PC1:/home/test/test# awk '{print NR,gsub(/e/,"&")}' test.txt > index.txt
    root@PC1:/home/test/test# ls
    index.txt  test.txt
    root@PC1:/home/test/test# cat index.txt
    1 4
    2 3
    3 3
    4 6
    root@PC1:/home/test/test# cp test.txt test.txt_bak  ## 备份原始文件
    root@PC1:/home/test/test# cat index.txt | while read {i,j}; do sed -i "$i s/e/xxx/$j" test.txt; done  ## 利用while循环 + sed 实现
    root@PC1:/home/test/test# cat test.txt  ## 最后一个e全部替换为xxx了
    e r e y e u xxx
    e e g xxx 3 h r
    1 3 e g e y xxx
    e s e e e e xxx

    3、如果一行中没有e

    root@PC1:/home/test/test# ls
    test.txt
    root@PC1:/home/test/test# cp test.txt test.txt_bak
    root@PC1:/home/test/test# ls
    test.txt  test.txt_bak
    root@PC1:/home/test/test# cat test.txt
    e r e y e u e
    d a f g 3 h r
    1 3 e g e y e
    e s e e e e e
    root@PC1:/home/test/test# awk -F "e" '{print NR, NF - 1}' test.txt ## 统计每行e的数目,并添加行号
    1 4
    2 0
    3 3
    4 6
    root@PC1:/home/test/test# awk -F "e" '{print NR, NF - 1}' test.txt | awk '$2 != 0'  ## 过滤掉没有e的行
    1 4
    3 3
    4 6
    root@PC1:/home/test/test# awk -F "e" '{print NR, NF - 1}' test.txt | awk '$2 != 0' > index.txt
    root@PC1:/home/test/test# cat index.txt
    1 4
    3 3
    4 6
    root@PC1:/home/test/test# cat index.txt | while read {i,j}; do sed -i "$i s/e/xxx/$j" test.txt; done  ## 利用while循环 + sed对最后一个e进行替换
    root@PC1:/home/test/test# cat test.txt  ##最后一个e替换为了xxx
    e r e y e u xxx
    d a f g 3 h r
    1 3 e g e y xxx
    e s e e e e xxx
  • 相关阅读:
    Qt5:快速设计对话框 QtDesigner 的使用
    Qt5:为菜单项添加图标 、 快捷键 和 状态栏 提示
    Qt5:在窗口上创建菜单栏
    Qt5:主窗口的创建 子类化QMainWindow
    AltiumDesigner设计快速入门
    AT24C02的MSP430驱动
    DSP_Builder设计方法说明_SinWave
    矩阵按键的MSP430驱动函数
    DAC8552使用说明
    PS2的FPGA解码模块
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/15690801.html
Copyright © 2011-2022 走看看