| Bytes | Lang | Time | Link |
|---|---|---|---|
| 049 | Zsh +coreutils | 250206T104827Z | roblogic |
| 008 | Japt R | 250206T083047Z | Shaggy |
| 012 | Retina | 250206T015635Z | Unrelate |
| 045 | JavaScript Node.js | 250206T010621Z | l4m2 |
| 063 | Python 3 | 210401T105032Z | thunder |
| 009 | Stax | 190104T200544Z | recursiv |
| 031 | Vim | 190103T223008Z | DJMcMayh |
| 010 | 05AB1E | 180810T150708Z | Mr. Xcod |
| 043 | Stacked | 170408T203740Z | Conor O& |
| 024 | k | 150922T185644Z | skeevey |
| 049 | Julia | 150717T153936Z | Glen O |
| 040 | Ruby | 150716T164239Z | manatwor |
| 111 | R | 150716T221522Z | MickyT |
| 100 | Gawk | 150717T154740Z | Rip Leeb |
| 081 | Julia | 150716T142643Z | Alex A. |
| 056 | JavaScript ES6 | 150717T135736Z | edc65 |
| 033 | Perl | 150716T200533Z | Toby Spe |
| 026 | sed | 150716T193035Z | aragaer |
| 055 | bash + sed + coreutils | 150716T143132Z | Thor |
| 217 | SWIProlog | 150716T141841Z | Fatalize |
| 9495 | Python | 150716T214146Z | TheCrypt |
| 014 | CJam | 150716T142108Z | Optimize |
| 075 | Python 2 | 150716T143035Z | Kade |
| 085 | JavaScript ES6 | 150716T192225Z | Downgoat |
| 052 | Haskell | 150716T175816Z | nimi |
| 031 | K | 150716T174557Z | kirbyfan |
| 014 | Pyth | 150716T142216Z | orlp |
| 086 | JavaScript | 150716T163201Z | Optimize |
| 098 | JavaScript ES6 | 150716T160927Z | rink.att |
| 112 | CoffeeScript | 150716T160348Z | rink.att |
| 159 | Java | 150716T144913Z | Geobits |
| 100 | Python 3 | 150716T143345Z | laurence |
| 149 | C# | 150716T142605Z | Sok |
| nan | 150716T140732Z | ProgramF |
Zsh +coreutils, 49 bytes
<<<$1>p;w=\ `sort p|tail -1`;cut -c${#w/[^ ]*}- p
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}
Japt -R, 8 bytes
·ËsFÕbrS
·Ë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
Retina, 12 bytes
m^/^\w/+`^.
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).*)^
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).
Python 3, 63 bytes
def f(s):return '\n'.join([l.strip() for l in s.splitlines()]);
Vim, 33, 31 bytes
qq/\v%^(\s.*\n?)*%$
:%s/.
@qq@q## Heading ##
Old version:
qq:g/\v%^(\s.*\n?)*%$/%s/.
n@qq@q
Stacked, noncompeting, 43 bytes
:lines'^ +'match$#'"!MIN' '*0# '^'\+''mrepl
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:
- We first split the input on newlines and take a copy (
qN/_) - Then the smallest column with non space character is calculated by transposing the newline separated array and then simply looking for the index of the first non-all-space row (
z{S-}#) - Then we simply remove that many characters away from each line (
f>) - Finally, we join by newline again (
N*)
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
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.
u .zgrabs all lines of stdin in an array, puts it inG. Then it evaluates the inner body, puts the result inG, and keeps doing this until it no longer changes (fixed point).!rhCG6transposesG, 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.The value from 2 is a boolean, which can be seen as an int 0 or 1.
>R Ggrabs this number and slices off that many characters off the left of each line inG. 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.jbjoins 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).