Search code examples
bashawksedcut

How to remove first n columns containing blanks from text file by linux shell scripting


I want to remove the first 6 columns containing blanks of this text file sample.txt

      2022-05-26 Mary  Jane
                 foo   bar
      2022-05-27 Tom   Powels
                 lorem ipsum
                 bar   foo
      2022-05-28 Honky Tonk
      2022-05-28 Hill  Billy
      ...

by linux shell scripting, e.g. by using sed, awk and/or cut.

Hence the expected output is

2022-05-26 Mary  Jane
           foo   bar
2022-05-27 Tom   Powels
           lorem ipsum
           bar   foo
2022-05-28 Honky Tonk
2022-05-28 Hill  Billy
...

I've searched in SE, but only found solutions to remove all blanks at the beginning of each line, e.g.

$ sed 's/^ *//' sample.txt > output.txt

which results in this file

2022-05-26 Mary  Jane
foo   bar
2022-05-27 Tom   Powels
lorem ipsum
bar   foo
2022-05-28 Honky Tonk
2022-05-28 Hill  Billy
...

where the formatting of the columns is lost.

Unfortunately this call of sed

$ sed 's/^ {6}//' sample.txt > output.txt

doesn't work.

Hence how could I remove the first 6 columns containing blanks by linux shell scripting?


Solution

  •  sed -E 's/^ {6}//' sample.txt > output.txt
     awk '{gsub(/^ {6}/,""); print > "output.txt"}' sample.txt