How to give space between columns?

前端 未结 4 1769
醉梦人生
醉梦人生 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
    
    0 讨论(0)
  • 2021-01-27 16:48

    I haven't tested it, But I guess this should work.

    awk '{$5=substr($5,0,1)" "substr($5,1);print}' your_file
    
    0 讨论(0)
  • 2021-01-27 16:57

    This is very specific to the format of your data, but it works:

    awk '{print substr($0,1,21)" "substr($0,22)}'
    
    0 讨论(0)
  • 2021-01-27 16:57

    assuming your fifth column starts with a single character,

    {
      if(sub(/^./, "& ", $5)) {
        print $0;
      } 
    } 
    
    0 讨论(0)
提交回复
热议问题