I have a text file containing aligned tabulated data with too much space separating columns, e.g.:

header1     header2          header3
val1a       val2a            val3a
val1bbbb    val2b b ab  ab   val3b

Note that the column values contain spaces. (The precise example is obtained by running COLUMNS=200 dpkg-query -l on Debian, up to removing the first few header lines.)

I would like to reduce the length of lines, namely, to merge adjacent columns that consist only of the space character to one single such column. The result here would be:

header1  header2       header3
val1a    val2a         val3a      
val1bbbb val2b b ab ab val3b

(Note that this may collapse several spaces within a field to a single space, as in "ab ab" => "ab ab" above, but this does not matter.) How could I do this? Thanks!

(The one solution I have assumes that the columns are separated by multiple spaces, so I can replace them with a delimiter that doesn't occur elsewhere in the file, and then re-columnate with column -t based on this delimiter. But this is fragile and unpleasant, and doesn't work if there are some columns that are just one space apart, or if some column values contain multiple spaces.)

  • your output result has different numbers of spaces between fields. It can not be considered as output with equally arranged field separator. In this case, the presented output looks also badly aligned as the initial input – RomanPerekhrest Jun 27 '17 at 9:46
  • 1
    @RomanPerekhrest: The point is that the input consists of tabulated data that was aligned with spaces, and the output also should. But note that in principle one could merge consecutive columns of the space character without trying to reconstruct the actual data columns. – a3nm Jun 27 '17 at 9:51
  • the question: between the 2nd and 3rd columns in the 1st line is 7 spaces, the result contains 4 spaces between them, by what rule it should be reduced exactly in that manner? – RomanPerekhrest Jun 27 '17 at 9:59
  • 1
    In your initial tabuated file, are all the coulmns (strictly) separated by \t? Can we safelly use \t (not space) as a delimiter in your initially file? – George Vasiliou Jun 27 '17 at 10:05
  • 2
    I don't see how one would know where a new column starts. – pfnuesel Jun 27 '17 at 15:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.