V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
maxduke
V2EX  ›  问与答

Linux BASH 文本处理求助

  •  
  •   maxduke · Nov 17, 2018 · 2097 views
    This topic created in 2717 days ago, the information mentioned may be changed or developed.
    有以下源文件 a.txt:

    # This is a file
    // Comments
    somechars
    somechars,somechar
    somechars,somechars,somechars

    需求:
    在有且只有一个逗号的情况下,在行末插入指定字符串。 在有 2 个逗号的情况下,在第二个逗号前插入指定字符串。

    输出效果 output.txt:

    # This is a file
    // Comments
    somechars
    somechars,somechar,STRTOBEINSERT
    somechars,somechars,STRTOBEINSERT,somechars


    求教如何实现这个效果,使用 sed/awk 都可以,多谢🙏
    6 replies    2018-11-17 19:56:58 +08:00
    ifaii
        1
    ifaii  
       Nov 17, 2018
    x='|STRTOBEINSERT|'
    perl -pe "s/(.*?)(,)(.*?)(,)(.*$)/\1\2\3$x\4\5/g || s/(.*?)(,)(.*$)/\1$x\2\3/g" filename

    我又复习了一次 perl 的用法
    ifaii
        2
    ifaii  
       Nov 17, 2018   ❤️ 1
    看错题目了,稍微改一下参数位置即可

    x='|STRTOBEINSERT|'

    perl -pe "s/(.*?)(,)(.*?)(,)(.*$)/\1\2\3$x\4\5/g || s/(.*?)(,)(.*$)/\1\2\3$x/g" filename
    l76862157
        3
    l76862157  
       Nov 17, 2018   ❤️ 1
    awk -F',' '{if(NF==2){print $0", STRTOBEINSERT"} else if(NF==3){print $1","$2", STRTOBEINSERT,"$3}else{print}}'
    DiamondbacK
        4
    DiamondbacK  
       Nov 17, 2018   ❤️ 1
    sed 's/[^,]*,[^,]*/&,STRTOBEINSERT/'
    gawk 'NF>1 {$2=$2 ",STRTOBEINSERT"} {print}' FS=, OFS=,
    uuspider
        5
    uuspider  
       Nov 17, 2018   ❤️ 2
    sed 's/\([^,]*,[^,]*\)\(.*\)/\1,STRTOBEINSERT\2/'
    maxduke
        6
    maxduke  
    OP
       Nov 17, 2018
    以上各位回复都感谢啦,🙏
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   6080 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 48ms · UTC 02:35 · PVG 10:35 · LAX 19:35 · JFK 22:35
    ♥ Do have faith in what you're doing.