Remove common leading spaces
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
Try it online here
Pyth, 19 18 17 14 bytes
jbu>R!rhCG6G.z
The implementation is pretty cool.
u .z
grabs 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).!rhCG6
transposesG
, 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 G
grabs 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.jb
joins the array of lines by newlines and prints it.
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)