How to remove leading spaces in multiple lines based on indent in first line

sedtext processinguniq

Processing a text line-by-line removing leading spaces on each line is easy:

$ LC_ALL=C git ls-files | sed -nE 's:^.*(\.[^./]+)$:\1:p' \
    | sort | uniq -c | sort -snr > lines # create example "lines" file
$ cat lines # "lines" example file
     30 .md
      8 .png
      4 .yml
      1 .css
      1 .gitignore
      1 .ico
      1 .sh
      1 .txt
$ sed -Ee 's/^ +//' lines # removing leading spaces (U+0020)
30 .md
8 .png
4 .yml
1 .css
1 .gitignore
1 .ico
1 .sh
1 .txt

However if only the first line should set the number of spaces to remove of all subsequent lines, how to achieve this? The output would look like:

30 .md
 8 .png
 4 .yml
 1 .css
 1 .gitignore
 1 .ico
 1 .sh
 1 .txt

What I'm trying to achieve is to pipe it to column(1) and make the output more dense but keeping the horizontal spacing across all lines. Simulation:

$ column -x lines | expand -t 8
     30 .md                   8 .png                  4 .yml
      1 .css                  1 .gitignore            1 .ico
      1 .sh                   1 .txt

Right now w/o trimming on the left a lot of space is in use as uniq(1) with the -c option adds them as it does right-justify the numbers (at position 8).

As long as I assume the maximum count is fixed, e.g. at maximum two digits long, I could hard-code it:

sed -Ee 's/^ {5}//' lines | column -x | expand -t 8
30 .md           8 .png          4 .yml          1 .css          1 .gitignore
 1 .ico          1 .sh           1 .txt

Best Answer

Gnu sed: store the leading whitespace in the hold and then strip away this much amount of leading whitespace from every line. Assuming the lines are sorted as shown.

sed -Ee '
  1{h;s/\S.*//;x;}
  G;s/^(\s*)(.*)\n\1$/\2/
' file

awk '
NR==1 {
  l0=length()
  $1=$1
  re = "^\\s{" l0-length() "}"
}
sub(re, "")+1
' file

perl -lpe '
  $x //= do{/^\s*/g;+pos;};
  $_ = substr($_,$x);
' file
Related Question