Treat spaces as spaces after n column

Viewed 51

How to run bash column command that after n columns it treats spaces as spaces and not as a separator?

Input:

field1 field2 field3 field 4 with spaces
foo1 foo2 foo3 foo4
bar1 bar2 bar3 bar 4 with spaces

Output:

col1    col2    col3    col4
field1  field2  field3  field 4 with spaces
foo1    foo2    foo3    foo4
bar1    bar2    bar3    bar 4 with spaces

Maybe replace spaces with other char before the column command and after that replace it again with spaces? awk or sed might be the right tool for this, but I'm not too familiar with them.

Any help is appreciated! Please, don't shoot me down. This is my first question here...

5 Answers

How about this

$ cat t
field1 field2 field3 field 4 with spaces
foo1 foo2 foo3 foo4
bar1 bar2 bar3 bar 4 with spaces

$ cat t | sed -E 's/^([^ ]+) ([^ ]+) ([^ ]+) (.+)$/\1\t\2\t\3\t\4/g'
field1  field2  field3  field 4 with spaces
foo1    foo2    foo3    foo4
bar1    bar2    bar3    bar 4 with spaces
$

Another awk that replaces first 3 spaces with a tab:

awk '{for (i=1; i<=3; ++i) sub(/ +/, "\t")} 1' file
field1  field2  field3  field 4 with spaces
foo1    foo2    foo3    foo4
bar1    bar2    bar3    bar 4 with spaces 

How about building another variable, here s4 to cause confusion:

$ awk '
BEGIN {
    OFS="\t"
}
{
    for(i=4;i<=NF;i++)
        s4=s4 (s4==""?"":" ") $i
    print $1,$2,$3,s4
    s4="" 
}' file

Output:

field1  field2  field3  field 4 with spaces
foo1    foo2    foo3
bar1    bar2    bar3    bar 4 with spaces

If there are multiple spaces like this, you need to set FS=" ".

Using awk and the example data in a file "spaces", while still utilising column:

awk '{ printf $1":"$2":"$3":";
for (i=4;i<=NF;i++) 
    { if (i != NF) { printf $i" " 
      } 
      else { printf $i 
      } 
    } 
    printf "\n" 
    }' spaces | column -t -s":"
       

Use awk to separate the first four fields with ":" and then pipe through to column using ":" as a separator.

This might work for you (GNU sed):

sed 'y/ /\t/;s/\t/ /4g' file

Translate all spaces to tabs and then replace the 4th tab and thereafter with spaces.

If you prefer a kind of symmetry:

sed 's/ /\t/g;s/\t/ /4g' file 
Related