g | x | w | all
Bytes Lang Time Link
049Zsh +coreutils250206T104827Zroblogic
008Japt R250206T083047ZShaggy
012Retina250206T015635ZUnrelate
045JavaScript Node.js250206T010621Zl4m2
063Python 3210401T105032Zthunder
009Stax190104T200544Zrecursiv
031Vim190103T223008ZDJMcMayh
01005AB1E180810T150708ZMr. Xcod
043Stacked170408T203740ZConor O&
024k150922T185644Zskeevey
049Julia150717T153936ZGlen O
040Ruby150716T164239Zmanatwor
111R150716T221522ZMickyT
100Gawk150717T154740ZRip Leeb
081Julia150716T142643ZAlex A.
056JavaScript ES6150717T135736Zedc65
033Perl150716T200533ZToby Spe
026sed150716T193035Zaragaer
055bash + sed + coreutils150716T143132ZThor
217SWIProlog150716T141841ZFatalize
9495Python150716T214146ZTheCrypt
014CJam150716T142108ZOptimize
075Python 2150716T143035ZKade
085JavaScript ES6150716T192225ZDowngoat
052Haskell150716T175816Znimi
031K150716T174557Zkirbyfan
014Pyth150716T142216Zorlp
086JavaScript150716T163201ZOptimize
098JavaScript ES6150716T160927Zrink.att
112CoffeeScript150716T160348Zrink.att
159Java150716T144913ZGeobits
100Python 3150716T143345Zlaurence
149C#150716T142605ZSok
nan150716T140732ZProgramF

Zsh +coreutils, 49 bytes

<<<$1>p;w=\ `sort p|tail -1`;cut -c${#w/[^ ]*}- p

49 bytes 52 bytes 62 bytes

Had to specify LC_COLLATE=C because of weird sort behaviour.


67 bytes, pure Zsh*

*with extendedglob and improvements by @GammaFunction

set ${(f)1};for w;C+=(${#w/[^ ]*})
x=${${(n)C}[1]};for w;<<<${w: x}

Try it online! 82bytes

Japt -R, 8 bytes

·ËsFÕbrS

Try it

·ËsFÕbrS     :Implicit input of string
·            :Split on newlines
 Ë           :Map each string in array F
  s          :  Slice the string to index
   FÕ        :    Transpose F
     b       :    First index that returns truthy (non-empty string)
      r      :      Globally replace
       S     :      Space
             :Implicit output joined with newlines

Japt -m, 6 bytes

With I/O as arrays of lines

sWÕbrS

Try it

Retina, 12 bytes

m^/^\w/+`^.

Try it online!

Funny coincidence this got bumped, because I've been trying and failing to think of a reasonable way to do the same thing for a Retina 0.8.2 solution to this challenge... Unfortunately, this relies on modern Retina's while loop to delete the first character of every line m`^. until ^+ one of them is alphanumeric /^\w/.

Retina 0.8.2, 26 23 bytes

+sm`(?<!(?=.*^\w).*)^ 

Try it online!

Not that this doesn't work... it just doesn't feel that reasonable! Essentially the same thing, but encoding the loop condition into the regex itself by nesting a positive lookahead inside a negative lookbehind (saving 3 bytes over my previous version which duplicated ^\w in a separate negative lookbehind and negative lookahead).

JavaScript (Node.js), 45 bytes

f=x=>/^\S/m.test(x)?x:f(x.replace(/^ /mg,''))

Try it online!

Python 3, 63 bytes

def f(s):return '\n'.join([l.strip() for l in s.splitlines()]);

Stax, 9 bytes

ü═≤+Σî║┘`

Run and debug it

Vim, 33, 31 bytes

qq/\v%^(\s.*\n?)*%$
:%s/.
@qq@q## Heading ##

Try it online!

Old version:

qq:g/\v%^(\s.*\n?)*%$/%s/.
n@qq@q

05AB1E, 10 bytes

|©ζ®gð*Ûζ»

Try it online!

Stacked, noncompeting, 43 bytes

:lines'^ +'match$#'"!MIN' '*0# '^'\+''mrepl

Try it online!

This works by finding the amount of spaces at the beginning of each line ('^ +'match$#'"!), getting the minimum, repeat a space that many times, and replacing that with nothing on each line.

k (24 bytes)

Takes a string as an argument and returns a string (with trailing new-line).

{`/:(&//&:'~^s)_'s:`\:x}

Example:

k) f:{`/:(&//&:'~^s)_'s:`\:x};
k) f"   a   b\n     c     d\n    e f"
"a   b\n  c     d\n e f\n

Julia, 72 62 61 57 54 49 bytes

g=s->ismatch(r"^\S"m,s)?s:g(replace(s,r"^ "m,""))

Ungolfed:

g(s)=
if ismatch(r"^\S"m,s)       # Determines if there's a newline followed by something other than a space
                            # Note: the m in r"^ "m says to work in multiline mode.
    s                       # If there is, return the string as the final result.
else                        # otherwise...
    m=replace(s,r"^ "m,"")  # Remove first space after each newline, and space at start of string.
    g(m)                    # Feed back into the function for recursion
end

Older solution (57 bytes):

g(s)=ismatch(r"
\S","
"s)?s:g(replace(s,"
 ","
")[2:end])

Original solution (72 bytes):

g(s)=all([i[1]<33for i=split(s,"\n")])?g(replace(s,"\n ","\n")[2:end]):s

Ruby: 77 73 70 66 65 58 57 40 characters

f=->t{t.gsub /^#{t.scan(/^ */).min}/,""}

Sample run:

irb(main):001:0> f=->t{t.gsub /^#{t.scan(/^ */).min}/,""}
=> #<Proc:0x00000001855948@(irb):1 (lambda)>

irb(main):002:0> puts f["   a   b\n     c     d\n    e f"]
a   b
  c     d
 e f
=> nil

irb(main):003:0> f["   a   b\n     c     d\n    e f"] == "a   b\n  c     d\n e f"
=> true

R, 118 111 bytes

Using the wonderful string functions of R :) This is similar/same to other solutions already posted. Input is through STDIN and cats to STDOUT.

cat(substring(a<-scan(,'',sep='|'),Reduce(min,lapply(strsplit(a,' '),function(x)min(which(x>''))-1))),sep='\n')

Test and explanation

> cat(substring(a<-scan(,'',sep='|'),Reduce(min,lapply(strsplit(a,' '),function(x)min(which(x>''))-1))),sep='\n')
1:                  a<-scan(,'',sep='|') # get the input lines
2:                                                         strsplit(a,' ') # split lines on spaces
3:                                                  lapply(                ,function(x)min(which(x>''))-1) # get min index - 1 for non space of each line
4:                                      ,Reduce(min,                                                      ) # get the min of those
5:        substring(                                                                                       ) # trim it off
6:    cat(                                                                                                  ,sep='\n') # output each line
7:
Read 6 items
              a<-scan(,'',sep='|') # get the input lines
                                                     strsplit(a,' ') # split lines on spaces
                                              lapply(                ,function(x)min(which(x>''))-1) # get min index - 1 for non space of each line
                                  ,Reduce(min,                                                      ) # get the min of those
    substring(                                                                                       ) # trim it off
cat(                                                                                                  ,sep='\n') # output each line
> 

Gawk, 101 100

{match($0,/^( +)/,t);if(t[1]<s||s==""){s=t[1]};z[NR]=$0;}END{for(r in z){sub(s,"",z[r]);print z[r]}}

For example...

cat input.txt | gawk '{match($0,/^( +)/,t);if(t[1]<s||s==""){s=t[1]};z[NR]=$0;}END{for(r in z){sub(s,"",z[r]);print z[r]}}'

Output...

a   b
  c     d
 e f

Julia, 93 92 81 bytes

Saved 10 bytes thanks to Glen O.

s->for i=(p=split(s,"\n")) println(i[min([search(j,r"\S")[1]for j=p]...):end])end

This creates an unnamed function that accepts a string and prints to stdout.

Ungolfed + explanation:

function f(s)
    # Split s into an array on newlines
    p = split(s, "\n")

    # Get the smallest amount of leading space by finding the
    # position of the first non-space character on each line
    # and taking the minimum
    m = min([search(j, r"\S")[1] for j in p]...)

    # Print each line starting after m
    for i in p
        println(i[m:end])
    end
end

JavaScript (ES6) 56

Recursive, trying to remove one space at a time from each row until a non-space is found.

Test running the snippet below - being ES6, Firefox only

f=s=>(r=s.replace(/^./gm,x=>(k|=x>' ',''),k=0),k?s:f(r))

// Test
test=
[[ "a", "a" ]
,["   abc", "abc" ]
,["   abc\n def\n  ghi", "  abc\ndef\n ghi" ]
,["    a\n    b\n    c", "a\nb\nc" ]
,["    a\n    b\n    c\nd", "    a\n    b\n    c\nd" ]
,["   a   b\n     c     d\n    e f","a   b\n  c     d\n e f" ]]

var tb=''
test.forEach(t=>{
  t[2]=f(t[0])
  t[3]=t[2]==t[1]?'OK':'FAIL'
  tb+='<tr><td>'+t.join('</td><td>')+'</td></tr>'
})
B.innerHTML=tb
td { white-space: pre; font-family: monospace; border: 1px solid#444; vertical-align:top}
#I,#O { height:100px; width: 200px }
<b>Your test:</b>
<table><tr><td><textarea id=I></textarea></td>
<th><button onclick='O.innerHTML=f(I.value)'>-></button></th>
<td id=O></td></tr></table>
<b>Test cases:</b><br>
<table ><tr><th>Input</th><th>Expected</th><th>Output</th><th>Result</th></tr>
<tbody id=B></tbody></table>

Perl, 47 33

Thanks @ThisSuitIsBlackNot for suggestion to use Perl's implicit loop

#!/usr/bin/perl -00p
/^( +).*(\n\1.*)*$/&&s/^$1//mg

The above is scored as 30 bytes for the line of code + 3 for 00p flags.

Original version, as a function:

sub f{$_=@_[0];/^( +).*(\n\1.*)*$/&&s/^$1//mgr}

This puts the argument into $_, then attempts to greedily match whitespace that's present on all lines with /^( +).*(\n\1.*)*$/ - if successful, $1 now contains the longest common prefix, and we execute the replacement s/^$1//mgr to delete it from the beginning of every line and return the resulting string.

Test

$ cat 53219.data
   a   b
     c     d
    e f
$ ./53219.pl <53219.data 
a   b
  c     d
 e f

sed - 26 bytes

:;/(^|\n)\S/q;s/^ //mg;b

run with -rz

Pretty straightforward:

  /(^|\n)\S/q;           - quit if there is a line that starts with non-space
              s/^ //mg;  - remove exactly one space in each line
:;                     b - repeat

-r option turns on extended regexps, -z reads whole input as a single string (actually uses NUL-byte as line delimiter)

bash + sed + coreutils, 74, 56, 55

Test data

s="\
   a   b
     c     d
    e f"

Answer

cut -c$[`grep -o '^ *'<<<"$s"|sort|line|wc -c`]-<<<"$s"

Output

a   b
  c     d
 e f

SWI-Prolog, 233 223 217 bytes

a(A):-b(A,0,0,0,N),w(A,N,0).
b([A|T],P,K,M,N):-P=1,(A=10,b(T,0,0,M,N);b(T,1,0,M,N));A\=32,(M=0;K<M),b(T,1,0,K,N);I=K+1,b(T,0,I,M,N).
b(_,_,_,N,N).
w([A|T],N,P):-P<N,A=32,Q=P+1,w(T,N,Q);put(A),A=10,w(T,N,0);w(T,N,P);!.

Edit: Completely changed my answer. It now uses character codes instead of strings.

An example of calling this would be a(` a b\n c d\n e f`)., with backquotes. You may need to use double quotes " instead if you have an old SWI-Prolog distrib.

Python, 94/95

lambda (94 bytes):

f=lambda s:'\n'.join(l[min(l.find(l.strip()) for l in s.split('\n')):] for l in s.split('\n'))

def (95 bytes)

def f(s):l=s.split('\n');m=min(i.find(i.strip())for i in l);return '\n'.join(i[m:] for i in l);

CJam, 20 14 bytes

qN/_z{S-}#f>N*

Algorithm:

Code Expansion

qN/               e# Read the entire input and split it on newline
   _z             e# Take a copy and transpose rows with columns.
                  e# Now we would have a bunch of all space rows. These rows are the ones
                  e# we want to remove (in form of columns) 
     {  }#        e# Get the index of the first item from the transposed array that returns
                  e# true for this block
      S-          e# From each part, remove spaces. If the part is all-space, it will return
                  e# an empty string, which is false in CJam. We finally will get the index
                  e# of the first non-all-space row (or column)
          f>      e# We take that index and remove that many characters from starting of each
                  e# row of the initial newline separated input
            N*    e# Join the array back using newlines and automatically print the result

Try it online here

Python 2, 86 79 75 Bytes

This can almost definitely be shortened some more, but right now it's not bad.

Thanks to xnor for saving 4 bytes!

s=input().split('\n')
for k in s:print k[min(x.find(x.strip())for x in s):]

JavaScript ES6, 85 bytes

s=>s.split`
`.map(z=>z.slice(Math.min(...s.match(/^ */gm).map(l=>l.length)))).join`
`

The new lines are significant

ES5 Demo:

function t(s) {
  return s.split("\n").map(function(z) {
    return z.slice(Math.min.apply(0, s.match(/^ */gm).map(function(l) {
      return l.length;
    })));
  }).join('');
}

// Demo
document.getElementById('go').onclick = function() {
  document.getElementById('r').innerHTML = t(document.getElementById('t').value)
};
Input:
<br>
<textarea id="t"></textarea>
<br>
<button id="go">Run</button>
<br>Output:
<br>
<pre style="background-color:#DDD;" id="r"></pre>

Haskell, 52 bytes

unlines.until(any(/=' ').map head)(map tail).lines

Usage example: unlines.until(any(/=' ').map head)(map tail).lines $ " abc\n def\n ghi" -> " abc\ndef\n ghi\n"

How it works:

                                           lines    -- split the input at newlines into a list of lines
        until                                       -- repeat the 2nd argument, i.e.
                                 map tails          -- cut off the heads of all lines
                                                    -- until the the first argument returns "True", i.e.
             any(/=' ').map head                    -- the list of heads contains at least one non-space
unlines                                             -- transform back to a single string with newlines in-between

K, 31 bytes

{`0:(&/{(0;#*=x)@*x}'" "=x)_'x}

Takes input a list of strings and prints the result to stdout.

Pyth, 19 18 17 14 bytes

jbu>R!rhCG6G.z

The implementation is pretty cool.

  1. u .z grabs all lines of stdin in an array, puts it in G. Then it evaluates the inner body, puts the result in G, and keeps doing this until it no longer changes (fixed point).

  2. !rhCG6 transposes G, gets the first element of the transposed array (the first column), strips it of any whitespace, and checks if there are any non-whitespace characters left.

  3. The value from 2 is a boolean, which can be seen as an int 0 or 1. >R G grabs this number and slices off that many characters off the left of each line in G. Step 1, 2 and 3 combined basically means that it will keep stripping off columns of whitespace until there is no pure whitespace column left.

  4. jb joins the array of lines by newlines and prints it.

JavaScript, ES6, 89 86 bytes

This one is totally using just RegEx matching and substitutions.

f=x=>eval(`x.replace(/(^|\\n) {${--`
${x}`.match(/\n */g).sort()[0].length}}/g,"$1")`)

// Snippet related stuff
B.onclick=x=>P.innerHTML=f(T.value)
<textarea id=T></textarea><br>
<button id=B>Trim</button>
<pre id=P></pre>

As always, Firefox only, since ES6. Will add ES5 version later.

JavaScript (ES6), 106 98 bytes

The newlines are necessary and are counted as 1 byte each:

f=x=>(a=x.split`
`).map(v=>v.slice(Math.min(...a.map(v=>(r=/^ +/.exec(v))&&r[0].length)))).join`
`

Demo

As with other ES6 answers, they only work in Firefox at the moment.

f=x=>(a=x.split`
`).map(v=>v.slice(Math.min(...a.map(v=>(r=/^ +/.exec(v))&&r[0].length)))).join`
`

// For demonstration purposes
console.log = x => X.innerHTML += x + `\n<hr>`;

console.log(f("a"));
console.log(f("   abc"));
console.log(f("   abc\n def\n  ghi"));
console.log(f("    a\n    b\n    c"));
console.log(f("    a\n    b\n    c\nd"));
console.log(f("   a   b\n     c     d\n    e f"));
<pre id=X></pre>

CoffeeScript, 112 bytes

f=(x)->(a=x.split "\n").map((v)->v[Math.min.apply(null,a.map((v)->(r=/^ +/.exec v)&&r[0].length))...]).join "\n"

Java, 159

Because there's a conspicuous lack of Java...

void f(String...a){int s=1<<30,b;a=a[0].split("\n");for(String x:a)s=(b=x.length()-x.trim().length())<s?b:s;for(String x:a)System.out.println(x.substring(s));}

It's just loops comparing length to trimmed length, then spitting out substrings. Nothing too fancy. For the scrollbar-impaired:

void f(String...a){
    int s=1<<30,b;
    a=a[0].split("\n");
    for(String x:a)
        s=(b=x.length()-x.trim().length())<s?b:s;       
    for(String x:a)
        System.out.println(x.substring(s));
}

Python 3, 100

def f(s):t=s.split("\n");return"\n".join([c[min([len(c)-len(c.lstrip(" "))for c in t]):]for c in t])

C#, 149 bytes total

Practically the same solution as ProgramFOX's, although the number of characters to trim is calculated manually.

using System.Linq;

And the function itself:

string D(string s){var l=s.Split('\n');int i=0;while(l.All(a=>a[i]==' '))i++;return string.Join("\n",l.Select(b=>b.Substring(i)));}

C#, 18 + 145 = 163 bytes

Requires (18 bytes):

using System.Linq;

Method (145 bytes):

string R(string s){var l=s.Split('\n');return string.Join("\n",l.Select(x=>string.Concat(x.Skip(l.Select(z=>z.Length-z.Trim().Length).Min()))));}

The method calculates the lowest amount of leading spaces on the lines and creates a new string built of all lines, with N chars skipped (where N is the previously calculated number).