How to give space between columns?

前端 未结 4 1770
醉梦人生
醉梦人生 2021-01-27 16:13

I have a text file as shown below.I would like to give a space between the character and number in the fifth column. How can I do this with awk?

cxe  911  bv  he         


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-27 16:36

    $ awk 'match($0,/([^[:space:]]+[[:space:]]+){4}[^[:space:]]/) {
             print substr($0,1,RLENGTH), substr($0,RLENGTH+1) }' file
    cxe  911  bv  heg   A 1029   53.030
    bvf  912  cv  lya   A 1030   51.99
    

    The "4" above is the number of columns before the one you're interested in, i.e. the 5th. If you want to operate on a different field, just change that number in the obvious way.

    If you're using an older version of gawk you'd need to add the --re-interval flag but for newer gawks RE-intervals ({4}) are enabled by default.

    Also, here's a briefer but GNU-awk specific solution if you prefer:

    $ awk '{print gensub(/(([^[:space:]]+[[:space:]]+){4}[^[:space:]])(.*)/,"\\1 \\3","")}' file
    cxe  911  bv  heg   A 1029   53.030
    bvf  912  cv  lya   A 1030   51.99
    

    You can do similar in any awk using a pair of sub()s but it's ugly so I'd use the match()/substr() for those awks.

    Finally if, as some others have posted, you want a solution to add a space after the 21st character on each line rather than after the first character in the 5th field on each line then that'd just be:

    $ awk 'sub(/.{21}/,"& ")' file
    cxe  911  bv  heg   A 1029   53.030
    bvf  912  cv  lya   A 1030   51.99
    

提交回复
热议问题