text:
Transpose a page of text
EDIT I modified the wording of the rules to make some things which were implicit more explicit. I also added some emphasis to clear up some points of apparent confusion, and explicitly defined the option of making a standalone program instead of a function.
The goal here is to make a function that takes a text file (or string) and transposes it so that lines become columns and vice versa.
Example:

I am a text.
Transpose me.
Can you do it?

Results in:

ITC
 ra
aan
mn
 sy
apo
 ou
ts
eed
x o
tm
.ei
 .t
  ?

The rules:

You are allowed to assume that the only whitespace characters used are " " and "\n" and that there is no trailing whitespace on any line.
You may assume that the file is ASCII. Which endline marker you want to use is up to you.(CRLF or LF). It must work correctly on the example, but it should also work on any input that satisfies the above assumptions.
You might have to insert spaces (as in the example) where there were none in order to keep the columns in line.
Your result must not have trailing whitespace on any line.
The final newline character(for the last line) is optional.
It should be either a function or a complete program. If your function accepts a string, then it should return the results as a string. If it accepts a filename, then you return the name of the file where you saved the result. You are additionally allowed to write a complete program that accepts input from STDIN and outputs the correct result to STDOUT; if you do this, you must not output anything to STDERR.
Shortest procedure wins, but I will upvote any answer I like.

Based on the rules, the output on the example is either 53 or 52 bytes long (for LF newlines) depending on whether the final newline is included or not.
Note: It is not a specific requirement, but if your function, when run twice successively is not identical to the original(the final newline might be differ, and any empty lines at the end of the file will be deleted), then you are probably breaking one of the rules.

I decided to remove the prohibition on language built-ins.

I edited to clarify the trailing whitespace condition.

Are you asking for a function? Is it acceptable to accept a string from STDIN and print the correct output to STDOUT?

@Quincunx Yes, I am accepting that as a "function".I will alter the rules to be explicit on that point.

The text transpose function cannot be an involution unless you allow for trailing ws. Example: "ac\ndef\n" ->TT-> "a\ncd\nef\n" ~ "a\ncd\nef\n" ->TT-> "acd\nef\n", where *=ws

@EmanuelLandeholm it wasn't intended to be perfect. It was intended to be an involution up to trailing whitespace. "You might have to insert spaces (as in the example) where there were none in order to keep the columns in line." This never requires a whitespace character to be inserted at the end of a line. The correct transformation  for your example according to the rules is:  "ac\ndef\n"->"ad\ne\ncf\n"->"a*c\ndef\n" Note there is no trailing whitespace at any step and on this input it is an involution.

Later duplicate: http://codegolf.stackexchange.com/q/85255

Are blank lines allowed in the input, eg "abc\n\ndef" ?

@LyndonWhite I don't remember anymore what I originally intended, but reading what I wrote, I would say yes.

Are trailing new lines allowed?

@AsoneTuhid I think at this point it is best to say, that is unspecified. If you are following the "no trailing whitespace" rule I don't think it should make a difference. But if it does, then choose whichever you prefer.

Japt, 6 bytes
y mx1R

Try itRun it twice - returns original string

Explanation
y

Transpose the input
m  R

Map over each line
x1

Trim right

R, 171
function(e){p=strsplit
x=t(plyr::rbind.fill.matrix(lapply(p(p(e,"\n")[[1]],""),t)))
x[is.na(x)]=" "
cat(apply(x,1,function(y)sub(" *$","",paste(y,collapse=""))),sep="\n")}

Usage example:
text <- "I am a text.
Transpose me.
Can you do it?"

(function(e){p=strsplit
x=t(plyr::rbind.fill.matrix(lapply(p(p(e,"\n")[[1]],""),t)))
x[is.na(x)]=" "
cat(apply(x,1,function(y)sub(" *$","",paste(y,collapse=""))),sep="\n")})(text)

ITC
 ra
aan
mn
 sy
apo
 ou
ts
eed
x o
tm
.ei
 .t
  ?

Trailing whitespace is removed.

 J (31 40)
f=:3 :';(,&LF@dlb&.|.)&.><"1|:>LF cut y'

This is a function that takes a string, and returns a string (i.e. a character vector with linefeeds inserted in the right places, and not a matrix.)
Edit: no trailing whitespace on any line.
Test:
   f=:3 :';(,&LF@dlb&.|.)&.><"1|:>LF cut y'

   string=:stdin''
I am a text.
Transpose me.
Can you do it?
^D

   $string
42
   $f string
53
   f string
ITC
 ra
aan
mn
 sy
apo
 ou
ts
eed
x o
tm
.ei
 .t
  ?

I hope you noticed I removed the prohibition for built-ins.

@Tim: Yes, otherwise I wouldn't have posted this.

Is the trailing whitespace rule written unclearly? You seem to have more characters than I expected.

How many characters should I have? The last characters on the string are ?\n.

53 I think. I intended that the lines shouldn't have trailing whitespace. So apparently it is unclearly worded. Maybe also not a reasonable requirement, since there are spaces in that position in the input.

You've got trailing whitespace on the mn, ts and tm lines.

I changed the wording now in the question. I can't/won't penalize you if you don't fix it though.

@Tim: it's fixed now.

I'm going to hold off a couple days before marking this as accepted in case someone post something surprising. But I think you got this one. Nothing shorter in APL?

@Tim: I could only get it to 44 in APL. Main reason is that APL doesn't provide either cut or dlb by default and writing them myself takes a bunch of characters even in APL.

Python 2.7 (97 79 94 90)
EDIT: Missed the function requirement;
I'm fairly sure this will be improved on since I'm sort of a beginner here, but to start with;
c=lambda a:'\n'.join(''.join(y or' 'for y in x).rstrip()for x in map(None,*a.split('\n')))

The code uses a simple split to split the string into a vector of rows. It then uses map with a function value as None (the unity function) and the splat operator to transpose and pad the vector (similar functionality to zip_longest in Python3)
The rest of the code just maps None to space, trims and reassembles the matrix to a single string again.
>>> a = 'I am a text.\nTranspose me.\nCan you do it?'
>>> c(a)
'ITC\n ra\naan\nmn\n sy\napo\n ou\nts\need\nx o\ntm\n.ei\n .t\n  ?'
>>> len("""c=lambda a:'\n'.join(''.join(y or' 'for y in x).rstrip()for x in map(None,*a.split('\n')))""")
88
# (+2 since `\n` is considered by `len` to be a single char)

Not exactly compliant. It should be a function take takes a string and returns a string.

@Tim Yes, missed that. Fixed now, thanks.

+1 you appear to be the shortest compliant python entry at the moment.

Nice use of map.  I keep looking for a place to use that... and you just beat me to it.  ;)

Ruby 111
Golfed:
def f t;s=t.lines;s.map{|l|l.chomp.ljust(s.map(&:size).max).chars}.transpose.map{|l|l.join.rstrip+?\n}.join;end

Ungolfed:
def transpose_text(text)
  max_length = text.lines.map(&:size).max
  text.lines.map do |line|
    line.chomp.ljust(max_length).chars
  end.transpose.map do |chars|
    chars.join.rstrip + "\n"
  end.join
end

Ruby has an array transpose function, so this simply pads the lines out, turns them into an array of characters, uses Ruby's Array#transpose function, then turns the array of characters back into lines.
Golfing it was simply using single-character identifiers, removing spaces, using a temporary for text.lines, and putting the calculation for max_length inline (there are no points for efficiency).

Nice. You can strip out one more character by replacing "\n" with ?\n.

Also, the .to_a is superfluous. You can gain another 5 characters there.

@O-I Thanks, I owe you six characters.  I dashed this off at work, which uses 1.9.3.  The to_a is required in 1.9.3, but not in 2.0.

I see. Good to know. Consider us even for showing me a few String methods in Ruby I should be using more often. Cheers!

Some of the code golf challenges have renewed my interest in learning ruby.

Bash+coreutils+sed, 83
eval paste `sed 's/.*/<(fold -w1<<<"&")/'`|expand -t2|sed 's/\(.\) /\1/g;s/ \+$//'

fold and paste do the important work.  The rest is just formatting.
Accepts input from stdin and outputs to stdout:
$ < tr.txt ./transposefile.sh
ITC
 ra
aan
mn
 sy
apo
 ou
ts
eed
x o
tm
.ei
 .t
  ?
$
m
m:=t
StringSplit,l%a%,o%a%
}
loop % m {
a:=A_index,n:=""
loop % o0
n.=(j:=l%A_index%%a%)=""?" ":j
s.=Rtrim(n," ") "`n"
}
return s
}

Test
text=
(
I am a text.
Transpose me.
Can you do it?
)
msgbox % f(text)

I can't test this one, but it looks compliant

Bash, 124 bytes
D=`mktemp -d`;split -l1 - $D/;for F in $D/*;do grep -o . $F>$F+
done;paste $D/*+|sed -e's/\([^\t]\)\t/\1/g;s/\t/ /g;s/ *$//'

It reads standard input and writes standard output. Try it:
echo $'I am a text.\nTranspose me.\nCan you do it?' | script.sh

How it works:

split input into single lines (files in temporary directory $D)
split lines into single characters using grep (files *+)
layout characters side-by-side using paste (TAB-separated columns)
remove alignment TABs, replace filler TABs with BLANKs, trim using sed

Edit:

-9: Removed tidy-up code ;rm -r $D (thanks Tim)
-2: use + instead of _ as suffix and shorten ${F}_ to $F+
-3: remove prefix L from split result files

For the purposes of code golf, you don't necessarily have to be nice and clean up after yourself. You can leave off the rm bit from your character count.

C (278 bytes)
Edit: This actually breaks the rules, since it takes a filename in as an argument but writes to stdout. I'll edit it later to write to a file and then print the filename to stdout.
This is my first code golf ever, so have mercy. Some plain old C. Place the input in test.txt and let it run!
clang transpose.c -o transpose && ./transpose test.txt
#import <stdio.h>
#import <stdlib.h>
#import <string.h>

#define BUFFER_SIZE 1024

#define MAX(A,B) ((A)>(B)?(A):(B))

int main(int argc, char **argv) {
    char line[BUFFER_SIZE];

    FILE *f; int nLines, maxLen;

    f = fopen(argv[1], "r");
    while(!feof(f) && fgets(line, BUFFER_SIZE, f)) {
        nLines++;
        maxLen = MAX(maxLen, strlen(line));
    }
    fclose(f);

    for (int charPos = 0; charPos < maxLen; charPos++) {
        f = fopen(argv[1], "r");
        for (int linePos = 0; linePos < nLines; linePos++) {
            fgets(line, BUFFER_SIZE, f);
            printf("%c", charPos < strlen(line) && line[charPos] != '\xA' ? line[charPos] : ' ');
        }
        printf("\n");
        fclose(f);
    }

    return 0;
}

By using short variable names, removing gratuitous formatting, and allowing file handles to leak, and disabling all warnings this is reduced to 278 bytes. (Since this uses implicit imports, it may not link properly on all systems. Works on my machine!)
#import <stdio.h>
int main(int C,char**V){char L[1024];int A,B,D,I,J,*F=fopen(V[1],"r");while(!feof(F)&&fgets(L,1024,F)){A++;D=strlen(L);B=B>D?B:D;}for(I=0;I<B;I++){F=fopen(V[1],"r");for(J=0;J<A;J++)fgets(L,1024,F)&&printf("%c",I<strlen(L)&&L[I]!='\n'?L[I]:' ');printf("\n");}}

I think you can take advantage of implicit int to shorten some of your declarations, or is that illegal now?

Yeah, I'm using that in a later edit to not import stdlib.h or string.h. If I don't import stdio.h it segfaults on run.

To your edit comment on the rules: your other alternative is to accept input from stdin. I would consider that conforming as well. And also, I can't tell from a cursory glance: does it strip whitespace from the ends of lines in the transpose version?

Since I re-read the file multiple times to avoid storing in RAM, reading from stdio would probably be harder. :)
I'm not sure what whitespace should be stripped. Right now I don't think it does any stripping at all, unfortunately. I'll have to work on that too.

You can declare A,B,D,I,J,*F as global variables, in order to avoid int keyword. Similarly, you can remove int from main declaration, and C argument. In C, int is optional in many places.

To answer which whitespace must be stripped. After transposition there is most likely going to be trailing " " characters on some lines. These should be deleted.

unlucky line break. The character in the quotation marks is a space.

Ruby: 88 characters
(Posted because it's shorter then the other Ruby solutions. Not checked whether my code introduces anything new compared to those. If you already posted a Ruby solution and you feel this is mostly a copy of yours, please comment and I will retire my answer.)
f=->t{l=t.split$/;r=[""]*m=l.map(&:size).max;l.map{|l|m.times{|i|r[i]+=l[i]||" "}};r*$/}

Sample run:
irb(main):001:0> f=->t{l=t.split$/;r=[""]*m=l.map(&:size).max;l.map{|l|m.times{|i|r[i]+=l[i]||" "}};r*$/}
=> #<Proc:0x99a9e68@(irb):1 (lambda)>

irb(main):002:0> sample='I am a text.
irb(main):003:0' Transpose me.
irb(main):004:0' Can you do it?'
=> "I am a text.\nTranspose me.\nCan you do it?"

irb(main):005:0> puts f[sample]
ITC
 ra
aan
mn
 sy
apo
 ou
ts
eed
x o
tm
.ei
 .t
  ?
=> nil

irb(main):006:0> puts f[f[sample]]
I am a text.
Transpose me.
Can you do it?
=> nil

+1 You golfed it better in any case.

Retina, 40 bytes
P`.+
~L0$`.
L,$.%'vs,$.(x$%=),`.+
m` *$

Try it online!
Based on this program that I created to transpose any size of rectangle, which uses Leo's suggestion for transposing a rectangle of a known size.
Edit: Golfed more and no longer has trailing spaces on lines.

Ruby — 144 characters
Here's my first attempt, golfed:
def f t
t.split(?\n).each{|l|l<<' 'until l.size==t.split(?\n).map(&:size).max}.map{|x|x.split('')}.transpose.map{|l|l.join.rstrip}.join(?/n)
end

For output, run puts f text where text is any multi-line string adhering to the rules above. The ungolfed version is below:
def text_transpose(text)
  lines = text.split(?\n)
  maxlen = lines.map(&:size).max
  lines.each { |line| line << ' ' until line.size == maxlen }
       .map  { |line| line.split('') }.transpose
       .map  { |char| char.join.rstrip }.join(?\n)
end

For a similar, but ultimately better solution in Ruby, check out Wayne Conrad's code above.

I didn't notice the transpose in your answer before I wrote mine.  It doesn't seem quite kosher for me to have essentially rewritten your answer, only a little better. :(

I don't mind at all. You came up with your code independently and it's not a race. I definitely learned something from your solution. Had you held back because I used transpose, it's possible a better Ruby solution wouldn't have surfaced. One of things I love most about programming is the willingness to collaborate and cross-pollinate ideas. Till we meet again, kind sir. Cheers!

PHP 194
function x($a){$a.="\n";$s=strlen($a);$i=0;while($c<$s)if($a{$c}!="\n")$b[$i++].=$a{$c++};else{$c++;for(;$i<$s;$i++)$b[$i].=" ";$i=0;}ksort($b);return rtrim(implode("\n",array_map("trim",$b)));}

Non-golfed:
function x($a) {
    $a.="\n";
    $s=strlen($a);
    $i=0;
    while($c<$s)
        if($a{$c}!="\n")
            $b[$i++].=$a{$c++};
        else{
            $c++;
            for(;$i<$s;$i++)
                $b[$i].=" ";$i=0;
        }
    ksort($b);
    return rtrim(implode("\n",array_map("trim",$b)));
}

This is my first golfing attempt, so please be kind! Also, tips/suggestions would be greatly appreciated!

It's shorter than my php attempt. You can save two characters by gitting rid of the "s around "trim". php will give a warning, but it works just fine.

@TimSeguine Warnings output on screen though right? You'll have to use @ to suppress warnings.

@eric I haven't been active in a while so the opinions might have changed, but in the past it was deemed acceptable to output irrelevant data to standard error.

It's allowed? If that is true, then I didn't know that.

MATHEMATICA 117 chars
t = "I am a text.\nTranspose me.\nCan you do it?";

f=(m=Length/@(f=Flatten[Characters/@StringSplit[#,"\n"],{{2},{1}}])//Max;
StringJoin@@@(PadLeft[#,m," "]&/@f)//Column)&

I can't test this one, so can you verify that it removes traling whitespace on the ends of lines? Also this doesn't appear(at first glance) to define a function, which the rules require.

hi @Tim, now it is a function f!.. tks

Perl (92+1)
reads stdin and writes to stdout.  adding 1 to the score for say
@L=map[grep!/\n/,split//],<>;do{$_=join'',map shift@$_||$",@L;s/ +$//;say}while grep@$_>0,@L

CJam, 32 25 bytes
CJam is newer than this challenge, so this answer is not eligible for being accepted.
Considerably shortened by user23013.
qN/_z,f{Se]}z{S+e`);e~N}%

Test it here.
qN/                       "Read input, split into lines.";
   _z,                    "Transpose, get length (find maximum line length).";
      f{Se]}              "Pad each line to that length with spaces.";
            z             "Transpose.";
             {         }% "Map this block onto each line in the result.";
              S+          "Add a space to ensure there's at least one.";
                e`        "Run-length encode.";
                  );      "Discard the trailing run of spaces.";
                    e~    "Run-length decode";
                      N   "Push a newline.";

Eligible or not, it is a great late answer. Seems like the hardest part for this answer was dealing with the trailing spaces.

@TimSeguine Indeed. Without a built-in trimming operator, doing this manually in CJam is surprisingly cumbersome (user23013's suggestion already improved it considerably).

Javascript, 103
s=>[...s].map((_,i)=>s.split`
`.map(b=>r+=b[q=b[i]||q,i]||' ',r=q='')&&r.replace(/ *$/,q?`
`:q)).join``

Less golfed
s=>[...s].map(
     // we need 'i' ranging from 0 to the length of the longest input line
     // so we scan all the input string, that is surely longer
     // but we need to check that after some point the output must be empty
     (_, i) => (
       r = '', // the current output row, starts empty
       q = '', // flag to check if we are beyond the longest line
       s.split('\n') // split in rows
       .map(
         b => ( // for each input row in b
           q = b[i] || q, // if there is a char at position i in b, i goes to q
           r += b[i] || ' ' // add to output the char at position i or a fill space
         )
       ),
       q // if q is still '', we are beyond the longest input line
       ? r.replace(/ *$/,`\n`) // trim leading space and add newline
       : '' // no output
     )
   ).join('')

Test

F=
s=>[...s].map((_,i)=>s.split`
`.map(b=>r+=b[q=b[i]||q,i]||' ',r=q='')&&r.replace(/ *$/,q?`
`:q)).join``

function go() {
  var text=I.value
  var output = F(text)
  O.textContent = output
}

go()
#I { width:50%; height:5em }
<textarea id=I>I am a text.
Transpose me.
Can you do it?</textarea>

<button onclick='go()'>Transpose</button>

Perl 5, 25 bytes
Note that this uses ANSI escape sequences and as such does not work on TIO, you can however see it in action here.
$"="";$_="[1;$.H@F"

Explanation
This code first changes the list separator ($") value to be a vertical tab, followed by the ANSI escape sequence for 'go backwards 1 column' (\x1b[1D), then we set the implicitly printed variable $_ to be a string that starts with the ANSI escape sequence for 'start printing at line 1 column $. (where $. is the current line of text)' (\x1b1;$.H) and interpolates the list @F (which is a list of all the characters on that line, populated  by autosplit (-a) with an empty split pattern (-F)) which places the contents of $" in between each item, moving the cursor vertically down instead of continuing output after the previous character.
Try it online!

Oh my god, the sheer horror! I love it!

 Scheme/Racket 113
The text:
(define t (list
    (string->list "I am a text.")
    (string->list "Transpose me.")
    (string->list "Can you do it?")
))

Without new lines and extra white spaces:
(define s(λ(v x)(if(= x 0)'()(cons(list->string(car v))(s(cdr v)(- x 1))))))(s(apply map list t)(length(car t)))

The user-friendly version
(define text (list
    (string->list "I am a text.")
    (string->list "Transpose me.")
    (string->list "Can you do it?")
))

(define transpose
    (λ(text length)
        (if (= length 0)
            '()
            (cons (list->string (car text)) (transpose (cdr text) (- length 1)))
)))

(transpose (apply map list text) (length (car text)))

Haskell
import Data.List
main = interact (unlines . transpose . lines)

It was so short, I needed to add in white space...

I'm almost sure you can remove some of the whitespace here. But otherwise, great solution.

This doesn't quite work on my system. It's a bit hard to show in a comment, but if you run it twice you get I am a text..? Transpose met Can you do i.

Yeah, I am thinking maybe you are not padding the lines to keep the columns intact like the example does. Theorectally, the result of running the function twice should be the original string(with possibly the addition or removal of the final newline.)

C++ (243 characters)
Here's a function that takes and returns a string.
I could've shaved a couple dozen chars, but decided to keep it as not-stupid code (runs fast, reads okay). Maybe I only decided to do that because this is my first code golf... I'm not hardcore enough yet :)
string f(string s){stringstream ss(s);vector<string> v;for(size_t i=0;getline(ss,s);++i){if(v.size() < s.size())v.resize(s.size());for(size_t j=0;j<s.size();++j){v[j].resize(i,' ');v[j].push_back(s[j]);}}s="";for(auto& i:v)s+=i+'\n';return s;}

With formatting:
string f(string s)
{
    stringstream ss(s);
    vector<string> v;

    for(size_t i = 0; getline(ss, s); ++i)
    {
        if(v.size() < s.size())
            v.resize(s.size());

        for(size_t j = 0; j < s.size(); ++j)
        {
            v[j].resize(i, ' ');
            v[j].push_back(s[j]);
        }
    }

    s = "";
    for(auto& i : v)
        s += i + '\n';

    return s;
}

I assume you use using namespace std;.

@xfix Not normally, but I did for this

If I am being picky, I would say using namespace std; should be added to the character count.

Python 2.7 - 115 chars:
oneliner:
>>> a
'I am a text.\nTranspose me.\nCan you do it?'

>>> "".join(["".join(i)+'\n' for i in zip(*[x+" "*(len(max(a.splitlines(), key=len))-len(x)) for x in a.splitlines()])])
'ITC\n ra\naan\nmn \n sy\napo\n ou\nts \need\nx o\ntm \n.ei\n .t\n  ?\n'

and in a cleaner printing:
>>> print "".join(["".join(i)+'\n' for i in zip(*[x+" "*(len(max(a.splitlines(), key=len))-len(x)) for x in a.splitlines()])])
ITC
 ra
aan
mn
 sy
apo
 ou
ts
eed
x o
tm
.ei
 .t
  ?

in 115 chars:
>>> len(""""".join(["".join(i)+'\n' for i in zip(*[x+" "*(len(max(a.splitlines(), key=len))-len(x)) for x in a.splitlines()])])""")
115

You are not stripping the trailing whitespace on your lines like the rules require.

Also, it's actually 116 bytes, \n is considered by len to be a single char, but it's two :)

@JoachimIsaksson on unix \n is one. So I say one is fine.

@Tim len("\n") will show 1, although it's certainly 2 separate characters in the source code. Saving the source to a file will make ls display 116. Just saying that len isn't the best way to measure code size due to escape characters being processed before measuring :)

@JoachimIsaksson oh, sorry I misunderstood your point.

GolfScript, 51 chars
n%.{,}%$-1=" "*:y;{y+y,<}%zip{n\+0{;).32=}do}%((;\+

This is a first attempt; I suspect it can be improved.  Most of the code is to comply with the padding and trailing space removal requirements — without them, just n%zip n* would suffice.
Ps. The following 46-character version will do the job for the given sample input, but will crash if any input column consists entirely of spaces:
n%.{,}%$-1=" "*:y;{y+y,<}%zip{0{;).32=}do]}%n*

I assume that's enough to disqualify it, even if the challenge doesn't explicitly say so.

Your assumption is correct. It should work on any ASCII text under the assumptions allowed in the rules.

Python 89 103 chars
def f(a):return'\n'.join([''.join(i).rstrip()for i in zip(*[j+' '*99 for j in a.split('\n')])]).rstrip()

I feel dirty. 90 104 chars for industrial strength version. :^)

not a function.

@Tim My bad, fixed. Anyway my solution is inferior to Joachim Isaksson's. I wonder if there's any short way to solve this problem with recursion.

Mathematica, 95 chars
f=""<>Riffle[Thread@PadRight@Characters@StringSplit[#,"\n"]//.{0->" ",{x___," "..}:>{x}},"\n"]&

K, 56
This should meet the spec now.
Accepts a string, returns a string.
{`/:{$[" "=*|x;|(+/&\" "=|x)_|x;x]}'x@'/:!max@#:'x:`\:x}

.
k)f:{`/:{$[" "=*|x;|(+/&\" "=|x)_|x;x]}'x@'/:!max@#:'x:`\:x}
k)f"I am a text.\nTranspose me.\nCan you do it?"
"ITC\n ra\naan\nmn\n sy\napo\n ou\nts\need\nx o\ntm\n.ei\n .t\n  ?\n"
k)f f"I am a text.\nTranspose me.\nCan you do it?"
"I am a text.\nTranspose me.\nCan you do it?\n"

The output appears to be an array of strings?

@Tim It is. If you want a single string then add three chars. {\/:x@'/:!max@#:'x:`:x}` for 26.

You also have a problem with trailing whitespace. And "If it accepts a filename, then you return the name of the file where you saved the result." You need to return output in the same manner you accept input.

@Tim should be fixed now. Kills my bytecount though

I suspected it might :( , but a spec is a spec.

Groovy, 98 chars
{i->o=[].withDefault{''};i.readLines().each{it.toList().eachWithIndex{c,d->o[d]+=c}};o.join('\n')}

online
ungolfed:
{i->
o=[].withDefault{''};//create list with empty string as default value
i.readLines()
.each{
    it.toList() //split every line to characters
    .eachWithIndex{
        c,d->o[d]+=c //append to string from list with right index
    }
};
o.join('\n')}//join list with newlines
}

J, 28 26 Bytes
Saved 2 bytes thanks to frownyfrog
t=.,@:(,&LF"1)@|:@:>@cutLF

Takes a string, returns a string. I'm not sure if there's a shorter version of the 'cutopen' function verb that I could use.
There's also the shorter
t=.|:@:>@cutLF

But I'm not sure it falls within the OP's guidelines, as it returns an array of characters.
How it works:
                     cutLF   | Splits the input on new lines and boxes them
                    @        | Composes verbs (as does @:, but they're not equal)
                   >         | Unboxes this, forming an array of the lines
                 @:          |
               |:            | Transposes the array
      (      )@              |
       ,&LF                  | Appends a new line...
           "1                | To each row of the array
    @:                       |
   ,                         | Flatten the result
t=.                          | Assign this verb to t

The other version works the same, but doesn't convert the transposed array to a properly formatted string.
Examples:
NB. Define a multi-line string

    text =: 0 : 0
I am a text.
Transpose me.
Can you do it?
)

    t text
ITC
 ra
aan
mn    NB. There's whitespace after the 'n' here, but I assume it doesn't count as trailing since it's part of the original string
 sy
apo
 ou
ts
eed
x o
tm
.ei
 .t
  ?

    t t text
I am a text.     NB. Again, whitespace here, but it's part of the argument of the second 't' (added by the first 't' to keep columns straight)
Transpose me.
Can you do it?

I would use cutLF.

Save 1 character with 0|:>@cutLF

C (MinGW), 272 262 259 254 234 229 228 bytes
-15 bytes thanks to ceilingcat
The TiO link requires the string.h include, but MinGW does not.
n,a,i,j;*f(int*s){char*p,**L=a=n=i=0,*r;for(;p=strtok(L?0:s,"\n");j>a?a=j:0)j=strlen((L=realloc(L,++n*8))[n-1]=p);for(p=r=calloc(n+1,a+1);i<a;i++,*p++=10){for(j=0;j<n;j++)*p++=i<strlen(L[j])?L[j][i]:32;while(p[-1]==32)p--;}s=r;}

Try it online!

Pyth, 11 bytes
# aYcw1;.tY

Try it online!
Takes input as a string, outputs a list of lists
Pyth, 25 bytes
# aYcw1=+Z1;jbcj"".n.tY)Z

Takes input as a string, outputs a string.
Try it online!

Lua, 203 189 bytes
t={{}}i=1m=0(...):gsub(".",function(c)n=#t[i]if c=="\n"then i=i+1t[i]={}else t[i][n+1]=c end m=m<=n and n+1or m end)
for x=1,m do for p=1,i do io.write(t[p][x]or" ")end _=m<=x or print()end

Try it online!
I saw another Lua solution here, but I don't think there's a problem with posting 2 solutions on the same language. If there is, tell me :)

There's nothing wrong with multiple answers in the same language. Even identical answers are allowed to an extent (though it's encouraged to at least check if you're posting the a similar solution)

Unfortunately Your result must not have trailing whitespace on any line.

But I can't see trailing whitespaces on the output of my code. There's no spaces after the line ends and no blank line at the end.

The part that seems to catch people out is on any line. e.g. This has extra whitespace on the second line

Ohhh now I got it! Sorry. I'll try to make it work as soon as I have time.
I think the problem was that there's only 1 example test and I thought that would be the "stress" test hahah But ok, thanks for telling me :)

Python 2, 87 101 bytes
lambda s:T('\n'.join(map(T,map(''.join,zip(*[t.ljust(len(s))for t in s.split('\n')])))))
T=str.rstrip

Try it online!

Unfortunately Your result must not have trailing whitespace on any line. Also it seems to print a lot of extra newlines.

@Jo King: Thx - My new toy did not work here!

This still has trailing whitespace on some lines for example

@Jo King: Ah yes. Fixed now.

MATLAB: 24 42 29 bytes
@(s)deblank(string(char(s)'))

Usage
s=["I am a text.";"Transpose me";"Can you do it?"];
@(s)deblank(string(char(s)'))
ans(s)

Output
ans =

  14×3 char array

    'ITC'
    ' ra'
    'aan'
    'mn'
    ' sy'
    'apo'
    ' ou'
    'ts'
    'eed'
    'x o'
    'tm'
    '.ei'
    '  t'
    '  ?'

Might be cheating here, as it's hard (as far as I can see) to get a string with newlines into MATLAB without using an array, so I went ahead and used an array for the input. Other than that, it does what it says on the tin - turns the string into a matrix of chars, transposes it and trims the whitespace.
Edit:
Changed (and lengthened) the program as I didn't see the requirement for whitespace to be trimmed.
Edit:
-13 bytes thanks to sundar.

"Your result must not have trailing whitespace on any line."

You don't need to include the f= in the byte count. And, you can probably shorten transpose(char(s)) to char(s)' (the single quote operator acts as a transpose here).

@sundar You're right! I use the single quote operator all the time but for some reason it totally slipped my mind while golfing... how annoying.

05AB1E, 6 bytes
ζεðÜ}»

Try it online.
Try it when taking the output as input-list again.
Explanation:
ζ         # Zip the input-list, swapping rows and columns
 ε  }     # For-each:
  ðÜ      #  Remove trailing spaces
     »    # Join the resulting list by new-lines (and output implicitly)

MATL, 5 bytes
!Z{Zv

Try it on MATL Online
Input is taken implicitly, and conveniently, the shorter lines get spaces added to them by the environment to make them all equal in length.
! - transpose
Z{ - Convert to cell array (since we'll need to hold arrays of different lengths after the next step)
Zv - deblank i.e. remove the trailing spaces

Octave, 35 29 bytes
@(s)strjoin(cellstr(s'),'\n')

Try it online!
(-1 byte thanks to Luis Mendo, -5 bytes thanks to strjoin from this SO answer)

You can remove the .. Best practices go out of the window in code golf :-P

@LuisMendo Ha, I didn't even realize I'd added the ., automatic muscle memory.

JavaScript, 102 100 bytes
q=>[...q].reduce((r,e,j)=>(y=w.map((e,i)=>w[i][j]||" ").join``.trimEnd())?r+y+`
`:r,"",w=q.split`
`)

Run it here:

f = q=>[...q].reduce((r,e,j)=>(y=w.map((e,i)=>w[i][j]||" ").join``.trimEnd())?r+y+`
`:r,"",w=q.split`
`);

console.log(f(`I am a text.
Transpose me.
Can you do it?`));

Seems like there is still potential to golf this; a lot of big names and movable snippets

Using the same basic idea, I was able to get 92 by replacing reduce with map then filter then join(sounds longer, but you save the ternary, an assignment and some parens)

without the string parameter golfing it looks like this: q=>[...q].map((x,i)=>w.map(x=>x[i]||" ").join("").trimEnd(),w=q.split("\n")).filter(x=>x).join("\n")

Nevermind, I realized that will delete empty lines

You've made me realize my solution incorrectly handles empty lines. Regardless, thanks for your solution.

PHP 227 217
Here's my attempt:
function f($s){$p=array_map;$s=$p(str_split,explode("
",$s));foreach($s as&$l)$l=array_pad($l,max($p(count,$s)),' ');array_unshift($s,null);foreach(call_user_func_array($p,$s)as$l)$r.=rtrim(implode($l))."
";return$r;}

Ungolfed:
<?php
function f($s) {
    $s=array_map(str_split, explode("\n",$s));
    foreach($s as &$l)
        $l=array_pad($l, max(array_map(count, $s)),' ');
    array_unshift($s, null);
    foreach(call_user_func_array(array_map, $s)as$l)
        $r.=rtrim(implode($l))."\n";
    return $r;
    }
$s="I am a text.
Transpose me.
Can you do it?";
echo f($s);
echo strlen(f($s));

Haskell: 191 chars
import Data.List
h [] = ' '
h (x:_) = x
t [] = []
t ([]:x) = t (" ":x)
t ((x:y):z) = takeWhile (any (/= ' ')).map (dropWhileEnd (== ' '))$(x:map h z):t (y:[s |(_:s)<-z])
m = (unlines.t.lines)

It's usually good to add some explanatory text. It helps those who don't know the language to decide to vote you up. :)

JavaScript, 177 173 bytes
s=>{l=s.split`
`.sort((a,b)=>b.length-a.length)[0];for(i=0,t=[];i<l.length;i++){t[i]=s.split`
`.map(i=>i+" ".repeat(l.length-i.length)).map(j=>j[i]).join``}return t.join`
`}

s=>{l=s.split`\n`.sort((a,b)=>b.length-a.length)[0];for(i=0,t=[];i<l.length;i++){t[i]=s.split`\n`.map(i=>i+" ".repeat(l.length-i.length)).map(j=>j[i]).join``;}return t.join`\n`}

If you can help me shorten this up, please do so.

Perl 5, 81 bytes
chomp(@a=<>);say((join"",map{(substr$_,0,1,"")||$"}@a)=~s/\s+$//r)while"@a"=~/\S/

Try it online!

PHP, 95+0 108+1 110 bytes
foreach($input as $s)for($y=0;~$c=$s[$y];)$r[$y++].=$c>"
"?$c:" ";echo rtrim(join("
",array_map(rtrim,$r)));

takes input from STDIN; breaks at the first empty line. Run with -nr or try it online.
Still trying to find something shorter than the additional rtrim to get rid of the second newline.

In general, I like this answer, but there are a number of issues; read the spec: "Your result must not have trailing whitespace on any line". Also, the rules for I/O are slightly ambiguous, but this isn't technically one of the allowed options, and this definitely isn't a complete program since you have to invoke the interpreter with non-default options.

Unless I am more rusty at PHP than I thought, the way you are calling file(f) will result in a warning being printed to stderr, which since you are using stdout as your output method is also not allowed. If there is a specific version of the PHP interpreter that no longer has this behviour(it used to IIRC), then please specify or correct me if I am wrong.

The simplest correction to everything but the endline issue that I can think of at the moment results in 8 additional characters. The simplest solution for the endline issue I can think of adds an extra 7. That still makes it by far the shortest PHP entry.

@TimSeguine 1) -n (no config file) tells the compiler to run with the default options. 2) The rules are ridiculous, but I´ll look into resolving the "issues" anyway.

@TimSeguine ... and the default options include error_reporting=E_ALL&~E_NOTICE (undefined constant "f", assuming string is a notice, not a warning)

If you don't like the rules then don't post an answer, it's that simple. Being able to follow a spec exactly is an important part of being a good engineer. I have relatively little interest in this site anymore, so any time spent on arguing about the spec is time I consider wasted.

@TimSeguine Sorry. let me rephrase: not "ridiculous" but "unusual". But ok. I´d love to see your solutions to the issues.

I have a few ideas for how to shave characters, but I don't have time to try any out for now. What I see is no reason to use $argn instead of STDIN for the purpose of the challenge. And is the $x=> important? looks like just a waste of 4 chars to me. If you are curious, the rules were an attempt at leveling the playing field with code golfing specific languages. How successful I was in that goal is debatable.

Lua, 205 bytes
L={}C=0 R=io.read I=R()while I~=""do L[C]=I C=C+1 I=R()end M=0 for i=0,C-1,1 do if#L[i]>M then M=#L[i]end end for i=1,M,1 do for j=0,C-1,1 do io.write(L[j]:sub(i,i)==""and" "or L[j]:sub(i,i))end print()end

Try it online!
Ungolfed
lines={}
count=0
R=io.read
input=R()

-- reads input in until an empty line is found
-- lines are added to the lines table
while input~="" do
    lines[count]=input
    count=count+1;
    input=R()
end

-- find the length of the longest string
max_len=0
for i=0,count-1,1 do
    if #lines[i]>max_len then
        max_len=#lines[i]
    end
end

-- loop through each character of each string
for i=1,max_len,1 do
    for j=0,count-1,1 do
        -- print the string's next character
        -- or a space if there is not another character
        if lines[j]:sub(i,i)=="" then--this if statement is golfed into a
            io.write(" ")            --pseudo-ternary statement in the golfed version
        else
            io.write(lines[j]:sub(i,i))
        end
    end
    print()
end

Pyth, 2 bytes
.t

Try it here!
Performs the built in transpose function on an input list, outputting a list of lines.

Pyth, 7 bytes
V.t.zdN

Try it here!
The above program, modified to use the input and output format specified in the challenge.

From the spec: "Your result must not have trailing whitespace on any line." - it caught me out as well.

Excel VBA, 154 bytes

Takes input from [A1] and outputs to the console.
x=Split([A1],vbLf):u=UBound(x):For i=0To u:l=Len(x(u)):m=IIf(m>l,m,l):Next:For i=1To m:For j=0To u:s=s+Mid(x(j)&String(m,32),i,1):Next:?RTrim(s):s="":Next

Ungolfed
x=Split([A1],vbLf)              ''  Split input by lines
u=UBound(x)                     ''  Get number of lines
For i=0To u                     ''  Iterate over lines
l=Len(x(u))                     ''  Get length of line `i`
m=IIf(m>l,m,l)                  ''  Compare to max length; Store Max
Next                            ''  Loop
For i=1To m                     ''  Iterate over chars in line
For j=0To u                     ''  Iterate over lines
s=s+Mid(x(j)&String(m,32),i,1)  ''  Append `i`th char of `j`th line to `s`
Next                            ''  Loop
?RTrim(s)                       ''  Remove right whitespace, print
s=""                            ''  Reset `s`
Next                            ''  Loop

K (oK), 43 bytes
Solution:
{"\n"/{(-+/&\32=|x)_x}@'+(|/#:'x)$x:"\n"\x}

Try it online!
Explanation:
Break on newlines, pad lines to same lengths, transpose, trim trailing whitespace and join on newlines. Feels like there has to be an easier way...
{"\n"/{(-+/&\32=|x)_x}@'+(|/#:'x)$x:"\n"\x} / the solution
{                                         } / lambda
                                         x  / input x
                                    "\n"\   / split (\) on "\n"
                                  x:        / save as x
                                 $          / pad right with left
                         (      )           / do this together
                            #:'x            / count (#:) each (') x
                          |/                / max
                        +                   / transpose
      {              }@'                    / apply (@) lambda to each (')
                    x                       / input x
                   _                        / drop
       (          )                         / do this together
                |x                          / reverse (|) x
             32=                            / equal to ASCII 32 aka " "
           &\                               / min
         +/                                 / sum
        -                                   / negate
 "\n"/                                      / join (/) on "\n"

A couple bytes can be saved by using {(-(|^x)?0)_x} to trim the trailing whitespace.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Code Injection works in C# too!
Given the following C# program outputting False, inject a 'malicious' line of code such that the program outputs True.
class Program
{
    static void Main()
    {
        System.Console.Write("False");
        ;
    }
}

Your answer should consist of a string that replaces the second semicolon, and causes the program to output True, the whole True and nothing but True (not even a newline). It must do this if stdout is printed to the console, and if stdout is redirected to a file.
The shortest answer wins.

What's your objective winning criterion?

@JB Do puzzles need a winning criterion? Will edit.

I'm mostly reacting to the code-golf remark, but the point stands: which will be the accepted answer?

@JB Shortest answer is best answer.

Well it is code-golf, then, isn't it?

@JB That's kind of a secondary goal, but I suppose I should add the tag.

I've added an additional criterion and changed it to Write instead of WriteLine

 52 characters
}static Program(){System.Console.Write(0<1);for(;;);

so the whole thing becomes:
class Program
{
    static void Main()
    {
        System.Console.Write( "False" );
    }
    static Program()
    {
        System.Console.Write( 0 < 1 );
        for ( ; ; ) ;
    }
}

Sorry for editing the question in the middle of your answer. Newlines are no longer allowed, you'll have to use Write.

Ok, I've changed WriteLine to Write

You could probably save some bytes by replacing your exit with for(;;);, nothing I've seen requires that the program terminates...?

@JoachimIsaksson Yes, that meets the requirements as specified.

}static Program(){System.Console.Write(0<1);for(;;); could always become }static Program(){for(System.Console.Write(0<1);;);

C#, 51 characters
Console.Write("\b\b\b\b\b");Console.Write("True ");

Will only work on standard output

First thing I tried, unfortunately it won't work because of the initial WriteLine.

Now it is Write :/ I don't get how we would manage to solve this if it keeps changing...

@Vereos I wanted to remove the ambiguity of 'newline or no newline'.

You don't need 2 instances of Console.Write, and you could use \r instead of 5 \bs. Console.Write("\rTrue ");

I don't think it meets the criteria.  It actually outputs False first, which is then overwtitten by True later.

You can generalize RamonBoza's answer to still work if stdout is redirected to a file.
Assuming the program runs under Mono on Linux, with the assembly Mono.Posix.dll loaded:
if(Mono.Unix.Native.Syscall.isatty(1))
{
    Console.Write("\rTrue ");
}
else
{
    // Truncate the output file first
    Console.OpenStandardOutput().SetLength(0);
    Console.Write("True");
}

I doubt this works on Windows, but there's probably an equivalent to isatty().

83... WIP
I was hoping this'd work, but apparently "False" isn't being interned as I'd hoped in my compiler
//}unsafe static Program(){fixed(char*f="False"){*(long*)f=0x65007500720054;*(f+4)=' ';}
}unsafe static Program(){fixed(char*f="False")for(int i=5;i-->0;)*(f+i)="True "[i];

ungolfed
class Program
{
    static void Main(string[] args)
    {
        Console.Write("False");
    }

    unsafe static Program()
    {
        fixed (char* f = "False") for (int i = 5; i-- > 0; ) *(f + i) = "True "[i];
    }
}

class Program
{
    static void Main()
    {
        System.Console.Write("False");

        System.Console.Clear(); System.Console.Write("True");

        Console.ReadLine();
    }
}

This won't work if stdout is redirected.

Not sure if this is accepted.
The question doesn't say anything about compiler options so I assume I can change the entry point of the app.
55 characters ,3 more than the accepted answer
}class P{static void Main(){System.Console.Write(1>0);}

Full
class Program
{
    static void Main()
    {
        System.Console.Write("False");
    }
    class P
    {
        static void Main() { System.Console.Write(1 > 0); }
    }
}

Welcome to the community!

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ Thanks. This is a fantastic site!!!

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Write a program that deletes itself
For this code golf challenge, you must produce a .exe runnable on windows. After running this .exe from any path with any name it must be deleted after execution.
My reason for limiting this to windows is something like this may be significantly easier if you have some niche OS.
Language(and code) used to produce the .exe is irrelevant, the file size of the executable is what will be measured for this. But still post the code used to produce it, along with the resulting file size.
This is code golf, but again the goal is the smallest executable file.

You give a reason for limiting to one only OS, but certainly not a reason to limit to windows.

@ArlaudPierre Well, I had to pick one, and (unfortunately) I have more experience with it.

Must the program delete only itself, or can it nuke, say, lots of other things as well?

@kojiro I think the point is to not have it be malicious, and to be able to be tested without fear of breaking a system.

@ArlaudPierre Also, notably, windows does not allow the deletion of a program while it is running. This increases the challenge level a bit.

Linux is totally a niche OS, where main(int a,char**b){unlink(*b);} is all you need. (Same goes for OSX.)

Is it allowed to strip and upx the exe?

@JanDvorak Now that's strange - you shouldn't vote an existing question as duplicate for a newer one. That's not in the spirit of this site.

@Howard why not? It's perfecly legitimate on SO

@JanDvorak This is a lot like copying someone's song/book/movie, changing a couple of words and the title, and then suing them for copying you. At the very least this should go through meta first to discuss this course of action, in my opinion.

@Gareth as if that didn't happen before.

@Gareth, no, its like writing a new book that is way better than the old book, and then publisher stops publishing the old book because nobody buys it anymore.

Assembly, 4608 bytes
The source code for the assembly program, using nasm syntax, is as follows:
BITS 32

GLOBAL _main
EXTERN _system

SECTION .data
cmd:    db      'echo>).bat start cmd /c del ).bat '
cmdarg: times 128 db 0

SECTION .text

_main:
        mov     eax, [esp + 8]
        mov     esi, [eax]
        mov     edi, cmdarg
copy:   lodsb
        or      al, al
        stosb
        jnz     copy
        push    cmd
        call    _system
        add     dword [esp], 5
        call    _system
        pop     edx
        ret

I built the executable using the following commands:
nasm -f win32 selfdel.asm
gcc -Wall -s -o selfdel.exe selfdel.obj

(I'm curious if the size of the executable would be different if MS's linker were to be used in place of gcc's, but I don't have access to MS development tools.)
Hopefully the code is straightforward enough to not need much explanation. Basically the program creates a batch file that deletes the program (as well as itself) after the program has exited.

Perl (11 bytes)
MZ+unlink$0

Save this as a.exe, or something, and run it with Perl. And yes, this is Win16 executable, except I don't know what it will do.

"And yes, this is Win16 executable" I do not believe this is true. I believe a Win16 binary needs to be an NE executable, in turn a subformat of an MZ executable, which needs to start with the two magic bytes MZ.

@nitro2k01: Added two magic bytes at the beginning.

"Win16 executable, except I don't know what it will do" I love it, this needs more votes

Tcl, 48
exec cmd /c "ping ::1&&del [file na [info n]]" &

Use a tclsh basekit to create the executable.
Note: a process can not delete its own executable, because it is locked when the process is running. So your only option is to get some other process to delete your executable when it stops running.

The final count goes by executable size, not source size

I think I should use C for that. A simple system call should do it. The entire Tcl runtime is a little bit big with 2.3MB.

https://codegolf.stackexchange.com/a/123067/29325

C - 857 byte source, 18,432 byte compilation
#include <stdlib.h>

size_t stringlen(const char *);
char * stringcat(char *, const char *);

main(int argc, char *argv[])
{
    if(argc > 0)
    {
        char *str = calloc(stringlen(argv[0])+11, sizeof(char));
        stringcat(str, "start del ");
        stringcat(str, argv[0]);
        system(str);
    }
}

/* Simple implementation of strcat to avoid including string.h */
char * stringcat(char *dest, const char *source)
{
    size_t i=0,j=0;
    while(dest[i] != '\0')
    {
        ++i;
    }

    while(source[j] != '\0')
    {
        dest[i+j] = source[j];
        ++j;
    }
    dest[i+j] = '\0';
    return dest;
}

/*Simple implementation of strlen to avoid including string.h */
size_t stringlen(const char *str)
{
    size_t i=0;
    while(str[i] != '\0')
    {
        ++i;
    }
    return i;
}

Compiled with:
gcc self-delete.c -pedantic -s -o self-delete.exe

It is now tested and works perfectly.

rm on windows??

@SztupY Sorry, I was not thinking :P

Python (59 bytes)
import os,sys;os.remove(sys._getframe().f_code.co_filename)

Assembly - 1548 bytes
Executes a delayed system command to find and delete itself
EXTERN system
IMPORT system msvcr100.dll

SECTION .text USE32
GLOBAL main
main:
    push string
    call [system]
    ret

string:
    db "start cmd /C ", 34, "timeout /t 3&for /f %a in ('dir /b *.exe') do (find ", 34, "someuniquestring134123asdfasd41324", 34,  " %a &if not errorlevel 1 del %a)", 34, 0

Compiled with:
nasm.exe -f obj filename.asm
alink.exe -oPE -entry main filename.obj

The executed script:
timeout /t 3
for /f %a in ('dir /b *.exe') do (
    find "someuniquestring134123asdfasd41324", %a
    if not errorlevel 1 del %a
)

HTML + JS (33)
<body onload=document.write('')>

“you must produce a .exe runnable on windows. After running this .exe from any path with any name it must be deleted after execution.” Not even close.


text:
Shrink a number string
Given a string of 1 and 2 of any length, write some code (doesn't have to be a function anymore, everything will be just fine) that calculates how many steps does it need to shrink the string to a final form, following this criterion:
If your string is 112112, this means that you have to print a 1, two 1s and a 2, like this:
1112. When you'll perform the operation again you'll have to print a 1 and a 2. You get 12. Then you print one 2, obtaining 2. This is a final form, since this string is not going to change anymore. Your code will output 3, since you needed 3 steps to get to the final form.
Other Rules

If the string has uneven length, the last number remains untouched.
Every string that cannot change anymore (like 222222) is considered a final form.
You cannot use any external source.
Your code must work with every string of 1 and 2.
Shortest code wins, as it is code-golf.
Your code should print every step.
Every input method will be fine.

Examples
Input >> 122122122121212212

Your code has to print:
211222111111222
11222111222
122111222
2111222
111222
1222
222
Steps:7 (you can omit the "Steps")
---- ---- ---- ----
Input >> 22222221

Your code has to print:
22222211
2222221
2
---- ---- ---- ----
Input >> 2222

Your code has to print:
0

EDIT: Heavily edited. So sorry about that.

"If your string is 112112, this means that you have to print a 1, two 1s and a 2, like this: 1112. " I don't get it.

Try to read it loudly. It's "one one", "two ones" and "one two". I mean, "1 time 1", "2 times 1" and "1 time 2".

If regexes are "not even useful", why do you ban them?

Regex restriction removed.

Uhm... I don't think it's fair to change the specification after 5 answers have been submitted (it has to be a function all of a sudden??). Besides, if it's supposed to be a function, shouldn't it return the answer, and not output it?

I didn't change nothing, I just highlighted it! Quincunx's answer made me think it was not that clear, so I set it bold. But yes, I guess that the function should return the answer. I feel like I'm messing it up, and I'm so sorry about that. :/

So... I guess it wouldn't be fair to make the users change the answers, so I'll edit it again, I'll just accept any function/program that gives the right output. Feel free to send any solution you'd like to.

"Every input method will be fine". An input method can do an arbitrary amount of preprocessing on the input, up to and including generating the answer as one long string. The "Python - 126" answer by Quincunx hints at this ambiguity (mentioning his answer could be 118 if ...) Seems like the "input method" needs to be more rigorously specified.

I really don't get it. How do you transform 112112 to 1112?

@user2460798 That was before I specified that. You can use whatever input method shortens your code. @ProgramFOX Like I said before, reading loudly really helps. If you divide the string in pairs, you get 11|21|12, right? Then, read the pairs: first is "One one", that means "a one", 1. Then we have "two one", which is "one, two times", so 11. Finally, we have "one two", that means "a two", 2. We could say that the first number tells how many times the second number must be repeated.

@ProgramFOX "one 1, two 1s, and a 2": 1 11 2. Every two numbers is a pair: the first number of the pair says how many times to render the second number in the pair. Any final odd digit without a pair partner is rendered as-is.

Ruby 1.9+, 73 characters
I see the no-regex rule as silly and arbitrary, so here's a spiteful regex based solution:
gets
($.+=1;puts$_.gsub!(/(.)(.)/){$2*$1.to_i})until~/^(22)*[12]?$/
p~-$.

Test run:
$ ruby 21.rb <<< 122122122121212212
211222111111222
11222111222
122111222
2111222
111222
1222
222
7

The last line is the number of steps.
Edit: Regex restriction has been removed by Vereos.

C - 156 154
My first code golf here!
f(char*s,c){puts(s);char*a=s,*b=s,m=50,x,y;while(*a){
x=*a++;y=*a++;if(y)m&=x&y;*b++=y?:x;x-49?*b++=y:(*b=0);}
*b=*a;return m/50?printf("%i",c),c:f(s,c+1);}

Test:
char c[] = "12211122211222221";
f(c,0);

Output:
12211122211222221
21112211222221
111221222211
121122221
21222211
1122221
122221
22211
22111
2211
221
10

GolfScript: 69 characters
0\{\)\.p.[]\{~10base{.,1>{(\(@\{''+*}++~@\+\.}{~+0.}if}do;}~.@=!}do;(

Every iteration of the inner loop finds the first 2 numbers in the string, and use them to form a block of the form {num1 num2 '' + *}.  When this block is evaluated, we get the desired reading of those numbers.  Repeat this until there are no more characters.  Then, repeat that loop while keeping track of the number of iterations and printing.
Sample:
echo '12211122211222221' | ruby golfscript.rb g.gs
"12211122211222221"
"21112211222221"
"111221222211"
"121122221"
"2122221"
"1122221"
"122221"
"22211"
"22111"
"2211"
"221"
10

Python - 126
def f(s):
 j=0
 while 1:
    n="";i=0
    for c in s:n+=c*i;i=[int(c),0][i>0]
    if i:n+=`i`
    if s==n:break
    s=n;print s;j+=1
 print j

This doesn't print the input value. If it needs to, then move print s; to right before n="";
Note: you said "function", so this is a function. Here is a version that is not a function (127 chars):
s=raw_input();j=0
while 1:
    n="";i=0
    for c in s:n+=c*i;i=[int(c),0][i>0]
    if i:n+=`i`
    if s==n:break
    s=n;print s;j+=1
print j

(If I can have the user paste the number in then 118 (paste data between quotes on first line)):
s="";j=0
while 1:
    n="";i=0
    for c in s:n+=c*i;i=[int(c),0][i>0]
    if i:n+=`i`
    if s==n:break
    s=n;print s;j+=1
print j

Sample run:
211222111111222
11222111222
122111222
2111222
111222
1222
222
7

As a bonus, each of these solutions work for strings containing larger numbers (up to 9), but some strings produce larger and larger outputs (for example, 99)

JavaScript, 107
(requires arrow function support, e.g. as in Firefox)
for(p=prompt,s=p(),k=0;r=s.match(/.?.?/g).map(a=>a>2?a[1]+(a<13?'':a[1]):a).join(''),p(s),r!=s;s=r)k++;p(k)

s is the input string

Each round, we use the regex .?.? to explode s into an array of two-character strings, then map those strings into their reduced forms and glue the array back together

r stores the result of the current round for comparison against the previous s

k is the round counter

We horribly abuse prompt (aliased to p) as both an input and output mechanism, since it can present a message to the user

for(p=prompt,s=p(),k=0;
    r=s.match(/.?.?/g).map(
        a=>
            a>2?                     // if a is more than one char
                a[1]+(a<13?'':a[1])  // double the second char if the first char is 2
               :a                    // if not two chars, return a
    ).join(''),                      // glue new array together
     p(s),                           // print s
     r!=s;                           // test if string has changed
    s=r)
        k++;
p(k)

PHP, 240
<?php
$s=$_GET['i'];$h=$s;for($t=1;$h!=r($h);$t++){echo$h.'
';$h=r($h);}echo r($s)==$s?0:$h.'
'.$t;function r($c){for($i=0;$i<strlen($c)-1;$i+=2){$s.=$c[$i]==1?$c[$i+1]:$c[$i+1].$c[$i+1];if($i+3==strlen($c))$s.=$c[$i+2];}return$s;}?>

Example:
http://skyleo.de/codegolf.php?i=211222111111222
211222111111222
11222111222
122111222
2111222
111222
1222
222
7

I'm kinda bad at codegolf ._.
Maybe I shouldn't use only Java and PHP (and I should think more complicated)

CodeGolf is not about finding the most complicated solution, but rather the most simple.

You don't really need to do str_split since you can access individual characters in a string just like an array in PHP.

Yeah, after some time I thought that myself, but I was too lazy to edit it. But now I changed it.

Perl - 50 (+2) bytes
$a-=print while"$_"ne(s/(.)(.)/$2x$1/ge,$_);$_=-$a

Requires -pl command line switches.
Sample usage:
$ more in.dat
122122122121212212

$ perl -pl rev-count.pl < in.dat
211222111111222
11222111222
122111222
2111222
111222
1222
222
7

$ more in.dat
22222221

$ perl -pl rev-count.pl < in.dat
22222211
2222221
2

$ more in.dat
2222

$ perl -pl rev-count.pl < in.dat
0

MATHEMATICA, 117
s="122122122121212212";
Grid@FixedPointList[(Partition[#,2,2,1,{}]/.{{1,1}->{1},{1,2}->{2},{2,1}->{1,1}}//Flatten)&,FromDigits/@Characters@s]

122122122121212212
211222111111222
11222111222
122111222
2111222
111222
1222
222
222

POWERSHELL, 2
Based on Vereos's response " You can use whatever input method shortens your code" to my question in the comments of the OP, the following script achieves the result:
$a

Example run for "122122122121212212":
# Input method is to assign answer to $a:
$a = @"
211222111111222
11222111222
122111222
2111222
111222
1222
222
Steps: 7
"@

# Execute script
$a

# Answer follows:
211222111111222
11222111222
122111222
2111222
111222
1222
222

Obviously this isn't a serious entry - it's purpose is to illustrate my point that allowing any input method can trivialize the actual code needed to yield the answer. Hence the input method needs to be more rigorously specified.

R, 158
s=utf8ToInt(scan(,""))-48;i=0;while(any(!!s-2)){t=(a<-sum(s|T))%%2;u=s[seq(a-t)];cat(s<-c(rep(u[c(F,T)],u[c(T,F)]),s[a*t]),"\n",sep="");i=i+1};cat("Steps:",i)

Example:
122122122121212212

211222111111222
11222111222
122111222
2111222
111222
1222
222
Steps: 7

J, 41 chars
As a function (ew parens! not terribly happy about them):
(,":@#)@}:@(([:;_2&(<@((".@[#])/)\))^:a:)

Exploded view
                _2&(            )\          NB. on non-overlapping 2-grams:
                       (      )/            NB.   insert between the two chars:
                        ".@[                NB.     read left operand ([) as a number
                            #]              NB.     and repeat right this many times,
                    <@(           )         NB.   then put it in a box
            ([:;                   )        NB. open and concatenate the boxes
           (                        ^:a:)   NB. repeat until fixpoint (keeping intermediates)
        }:@                                 NB. drop first element (the input)
(,":@#)@                                    NB. append length of array (# steps)

Sample run
   (,":@#)@}:@(([:;_2&(<@((".@[#])/)\))^:a:) '1121121'
1121121
11121
121
21
11
5
   (,":@#)@}:@(([:;_2&(<@((".@[#])/)\))^:a:) '122122122121212212'
122122122121212212
211222111111222
11222111222
122111222
2111222
111222
1222
7

Perl, 107 chars
The other perl code clearly beats this, but for what it's worth, here it is. I used the -l switch at the cost of an extra character:
$_=<>;while(1){$l=$_;$_=join"",map{($a,$b)=split//;$b?$b x$a:$a}grep/./,split/(..?)/;last if$l eq$_;print}

A more legible version of that:
$x = <>; while(1) { $l = $x; $x = join "", map{ ($a,$b) = split//, $_; $b ? $b x $a: $a } grep /./, split /(..?)/, $x; last if $l eq $x; print $x}


text:
Verify Brainfuck program
Yet another Brainfuck parsing problem, but this time... different.

You are working in the Infinite Monkeys Incorporated, the company making Brainfuck programs, to solve various interesting problems (by accident, no less - after all, the company makes random programs). However, it appears that your fast Turing machines that only execute Brainfuck have a small and expensive problem with syntax errors - make one, and the computer explodes. It's probably a design flaw, but nobody had bothered to find why it happens.
As Turing machines (especially fast ones) are expensive (after all, they have infinity RAM which costs), it would be better to make sure that the program doesn't have any syntax errors before executing the code. Your company is going to run lots of code, so manual verification won't work. Write a program that reads the STDIN for Brainfuck code, and exits with exit status set to anything other than 0 (error) if program has any syntax error (for example, ] is a syntax error, because there is no matching [). Exit with exit status set to 0 if the program is completely fine.
Make sure that your program correctly notices mistakes involving []. You wouldn't want another computer to explode, would you? Oh, and make sure it's as short as possible - your boss pays for short programs (because he thinks they are fast, or something). Oh, and you don't have to code in Brainfuck (in fact, you cannot, because Brainfuck doesn't support exit codes) - your code will be ran on normal computer.

So, as you can see, your job is to check if Brainfuck program is "valid" (has paired [] symbols). Please note that Brainfuck programs can have other characters than [], so don't refuse the program just because it has other commands. Smallest code wins, but probably you would care more about upvotes anyway.

What about languages that don't allow setting a process exit code?

@KendallFrey: Simple, use something else. Or in GolfScript, embed Ruby code. Perhaps this blocks some esoteric programming languages, but well...

Is it okay to set the error code to something other than 1 (as long as it's not 0 of course) on failure?

@marinus: I don't know why you would want that, but I think it's fine.

@GlitchMr: because then I can use GCD(a,b) instead of 0 != a || b.

Does this solely consist of checking that every [ has a matching ]?

@PeterTaylor: Yes.

So you consider the following BF program valid: <+ ? What will your Turing machine do?

@vsz: It is valid, because the program begins in middle of infinite tape. But I guess this makes sense.

GolfScript, 18 chars
.{[]`?)},~](`91?./

This code runs successfully with exit code 0 (and prints some garbage to stdout) if the square brackets in the input are balanced.  If they are not, it fails with a non-zero exit code and prints an error message to stderr, e.g.:
(eval):2:in `/': divided by 0 (ZeroDivisionError)

or
(eval):1:in `initialize': undefined method `ginspect' for nil:NilClass (NoMethodError)

Since the challenge said nothing about output to stdout / stderr, I figure this qualifies.  In any case, you can always redirect those to /dev/null.
Explanation:
The code {[]`?)}, strips everything but square brackets from the input, and the ~ evaluates the result as GolfScript code.  The tricky part is that unbalanced brackets are perfectly legal in GolfScript (and, indeed, my code includes one!), so we need some other way to make the code crash.
The trick I'm using is to leave a copy of the input at the bottom of the stack, collect the entire stack into an array (using the unbalanced ]) and shift the first element off.  At this point, three things can happen:

If the input ended in an unclosed [, trying to shift an element off an empty array will crash the interpreter (which, in this case, is exactly what we want!)
If the brackets in the input were balanced, the shifted element will be the original input string.
Otherwise (if the input had an unopened ] or an unclosed [) it will be an array.

My original 14-char entry then compared the shifted value with a string, which would crash if it was a nested array.  Unfortunately, it turns out that comparing a flat (or, in particular, empty) array with a string is also legal in GolfScript, so I had to switch tack.
My current submission, instead, uses a very brute-force method to tell arrays from strings: it un-evals them and tries to find the first occurrence of [ (ASCII code 91), which will be zero if and only if the un-evaled variable was an array.  If so, dividing the zero with itself triggers the desired crash.
Ps. Two other 18-char solutions are:
.{[]`?)},{.}%~](n<

and
.{[]`?)},~]([n]+n<

Alas, I haven't yet found a shorter way to solve the "empty array problem".

is this balanced?: ][ (ie does it fail in your program?)

@Quincunx: It fails, as it should.

However, it did turn out to accept [[]; I've fixed it now, at the cost of 4 chars, and it passes all my tests now.

If I understand you correctly, you had a 14-char solution which fails to distinguish between a string and an array only in the case that the array is empty. 1+ will turn an empty array into a non-empty array, an non-empty array into a non-empty array, and a string into a string.

@PeterTaylor: Yes, it was .{[]`?)},~](n<. I did try your 1+, but it seems that the array needs to contain something other than a number (presumably so that the interpreter will crash when it tries to recursively compare a character with an array/string). Using n+ doesn't work either, since it coerces the array to a string; [n]+ does work, but still puts me at 18 chars.

I don't understand why the Befunge solution is accepted and not this one. This is shorter. Also, I don't understand why it has so many more upvotes than this one.

@Quincunx: Well, the reason is simple - I simply haven't noticed this answer. It's now fixed (I know, two months later).

Brainfuck 76 bytes
>>+[<+++++++++[->---------<]+>-[--[[-]<->]<[<[->-]>[<+]<]>]<[-<+>]+>,]<<[<+]

This goes out of it's bonds if square brackets are unbalanced turning the bf interpreter/compiler to fail runtime and some of them have exit codes to reflect that.
requires eof=0, wrapping values and finit number of cells
In Ubuntu you can use the interpreter bf (sudo apt-get install bf)
% echo '[[[]' | bf -n bf_matching.bf
Error: Out of range! Youwanted to '<' below the first cell.
To solve, add some '>'s at the beginning, for example.
an error occured
% echo $?
5
% bf -n bf_matching.bf < bf_matching.bf
% echo $?
0

I like how you used Brainfuck even though the question said that was impossible.

Oh, wow. I'm honestly surprised. I assumed it was impossible, but it's not.

@xfix: Brainfuck is turing-complete so it can do anything (given the I/O constraints.)

@marinus Turing completness only means it can do all computations. Brainfuck is Turing complete without I/O as you can run a program that calculates any calculation and see the result by inspecting it's memory after running. BF without I/O would make people less interested as it would be difficult to make utilities. e.g. i could never have made my lisp interpreter.

Befunge 98 - 26 31 20 19 chars
~:']-!\'[-!-+:0`j#q

Got rid of some massive conditionals. Now the program works as follows:
~:   read an input char and duplicate it

']-! push a 1 if the char is the ] char, 0 otherwise

\    swap the comparison value for the duplicated input char

'[-! push a 1 if the char is the [ char, 0 otherwise

-    subtract the two comparison values. If the second one is 1, the first is 0,
     so the result is -1. Else if the second one is 0, the first is 1 and the result is
     1. Else, the first and the second are both 0 and the result is 0

+    Add the number to the counter (which is 0 if there is none already)

:0`  test if the counter is positive (that'd mean an invalid program). Pushes a 1 if
     positive, 0 otherwise.

j#q  if the counter is positive, then this jumps to the q. Otherwise, it skips the q
     and continues to the ~ at the beginning of the line. If there are no more chars in
     the input, then the IP will be sent back to the q.

q quits the program and pops the top value as an error value. The error value will be -1 1 if there are too many ]'s, 0 if they are balanced, and positive negative if there are too many ['s. If the number is positive negative, then that many the absolute value of that number ]'s are needed to balance the program.
Edit: Switched increment and decrement. [ used to increment the counter and ] used to decrement it. By switching it, I save 1 char, because for the exit condition, I only have to check if the counter is positive, rather than negative.

Old version
~:'[-!j;\1+\#;']-!j;1-#;:0\`j#q

This code works as follows:
~    read one char of input
:    duplicate it
'[-! push 1 if the character is [, 0 otherwise
j    jump that number of characters
;    skip until next ;
\1+\ increment counter

similarily for ].

#q when end of input is reached, ~ reflects the IP back. q ends the program with the error value on the stack.

Edit: realized that this accepted inputs like ][, now it ends whenever the count gets negative, using
:0\`j

18 bytes

@JoKing that's pretty nice, using the distance between [ and ] to do the comparison with both.

ruby (64)
exit $<.read.tr('^[]','').tap{|x|0while x.gsub!('[]','')}.empty?

previously (68) it was:
exit ARGF.read.tr('^[]','').tap{|x| 0 while x.gsub!('[]','')}.empty?

Another equivalent solution uses
exit $<.read.tr('^[]','').tap{|x|0while x.gsub!('[]','')}.size>0

can't use size alone because it would give false negatives (!!!) when the total number of unbalanced brackets is multiple of 256

This is codegolf. I'm sure you can remove some whitespace here. Ruby is somewhat whitespace sensitive, but it ignores it in many cases. To begin with, you don't need whitespace near = operator.

better version (somewhat inspired by the sed+tr solution). I'm not sure I can get much better than this. At least it has as low as 4 whitespaces!

And yet, I can remove two of them.

I think the spaces around the 0 can go.

J (38 35)
exit({:+.<./)+/\+/1 _1*'[]'=/1!:1[3

Explanation:

1!:1[3: read stdin
'[]'=/: create a matrix where the first row is a bitmask of the [s in the input, and the second row is the ]s.
1 _1*: multiply the first row by 1 and the second row by -1.
+/: sum the columns of the matrix together, giving delta-indentation per character
+/\: create a running total of these, giving indentation level at each character
({:+.<./): return the GCD of the final element ({:) and the smallest element (<./). If all the braces match, both of these should be 0 so this will return 0. If the braces do not match, it will return a nonzero value.
exit: set the exit value to that and exit.

Nice breakdown...

Perl, 30 characters
Your basic Perl recursive regex to the rescue:
perl -0ne 'exit!/^(([^][]|\[(?1)\])*)$/'

For those unfamiliar with the command-line arguments used here: -0 allows one to set the line-ending character for the purposes of file input; using -0 with no argument sets the line-ending character to EOF. -n automatically reads the input (in this case, the entire file) into $_ beforehand.
If the regex matches, it returns a true value, which is negated to 0 for the exit code. Otherwise, the false return value yields an exit code of 1.

Guess I'll have to golf my answer better to beat this 30 char solution.

There. My solution is now much shorter than it was before. Nice solution. +1

bash (tr + sed) - 42
[ -z `tr -Cd []|sed ":a;s/\[\]//g;t a"` ]

If you don't mind error messages then you can remove the last space between ` and ] to get length 41.

Unless I miss anything, you have useless use of cat and $() (also "[]" can be written as []). I accepted this answer, but until I will see improvements in length, I'm not going to upvote this, as while short, it could be way shorter for bash.

Well, actually I don't know shell scripting that well. I'm unable to make most of those work. I replaced $() with backticks and did the "[]" -> [] you suggested.

There is still useless use of cat.

I could've sword I tried and failed this, but I was wrong.

Perl (56 chars)
$/=0;$r=qr/[^][]*(\[(??{$r})\])*[^][]*/;<>=~m/^$r$/||die

The obvious Perl solution: a recursive regex. Unfortunately it's a rather verbose construct.

C, 73 64 chars
Thanks to suggestions from breadbox (although this probably requires little-endian to work):
i;main(c){while(read(0,&c,1)*(i+1))i+=(c==91)-(c==93);return i;}

How it works:

implicit int global i gets initialized to 0
c becomes an implicit int which gets argc (initialized to 1 but we don't care, just as long as the higher bits aren't set)
read(0,&c,1) reads a single character into the low byte of c (on little-endian architectures) and returns 0 at EOF; i+1 != 0 unless the balanced bracket quote goes to -1; multiplying them together works as a (safe) boolean AND that takes one less char than &&
c==91 evaluates to 1 for '[', and c==93 evaluates to 1 for ']'. (There might be some fiddly bit-fiddling trick that would be smaller but I can't think of anything.)
return i exits with status code 0 if it's balanced, non-zero if it isn't. Returning -1 technically violates POSIX but nobody actually cares about that.

Previous version:
main(i){char c;i=0;while(read(0,&c,1)*(i+1))i+=(c==91)-(c==93);return i;}

Using getchar() instead of read will shorten the code and allow you to use (implicit) int instead of char for your variable.  Also remember that globals are automatically initialized to zero.

Thanks, I forgot about getchar(). Not sure how the global init helps, though - defining a global int i takes more characters than using the implicit argc one.

Globals can also be implicit. Outside of a function c; defines a global int.

Meanwhile, getchar(c) ends up not making it any shorter, at least using this approach, because it needs to be tested for >=0 in some way, and an implicit int for c passed into read() isn't guaranteed to work due to endianness.

What about ][ ? I'm sure it's not balanced. Don't you have to keep track whether it goes negative at least once?

@vsz That's covered, by the *(i+1) loop exit condition.

Haskell (143)
import System.Exit
f=exitFailure
v c []|c==0=exitSuccess|True=f
v c (s:t)|c<0=f|s=='['=v(c+1)t|s==']'=v(c-1)t|True=v c t
main=getContents>>=v 0

to jgon: Using 2 guards seems to be more dense than if-then-else. Also, I don't think yours checks that the brackets are in the right order ("][" passes)

oh wow, only saw this comment when it was pointed out today. Fixed my code, but yeah nice, guards do seem to be denser (+1).

Turing Machine Code, 286 272 bytes
Again, I'm using the rule table syntax defined here.
0 * * l 1
1 _ ! r Q
5 _ _ r 5
5 * * * W
W [ ! l E
W ] ! l T
W _ _ l I
W * ! r *
E ! ! l *
E * * * R
R _ [ r O
R * * l *
T ! ! l *
T * * * Y
Y _ _ r U
Y * * l *
U [ _ r O
U ! ! * halt-r
I ! ! l *
I _ _ r halt
I * * l halt-r
O ! ! r Q
O _ _ l I
O * * r *
Q ! ! r *
Q * * * W

Terminates in state halt to accept the input and halt-r to reject it.

halt-err can be shorter, such as halt* for example.

Lua, 56
os.exit(("["..io.read"*a".."]"):match"^%b[]$"and 0 or 1)

"^%b[]$" what is this? Can you explain? Surely, this isn't regex?

@Cruncher: It's not. It's Lua pattern, not regex (Lua patterns are similar to regexes, but they aren't). In this case it matches the beginning of string (^), balanced set of [ and ] with anything inbetween (%b[]), and end of string ($).

Ruby, 59 58
Scans for opening and closing bracket, counting [ as 1 and ] as -1, and  exits if the count drops below 0.
b=0
$<.read.scan(/\]|\[/){exit 1if(b+=92-$&.ord)<0}
exit b

Upvoted, and shortened by one character (I removed whitespace after exit 1 in case you ask).

GTB, 55
0→O:0→X[`I@I="[":X+1→X@I="]":X-1→X@X<0:1→O@!!Ig;e]l;e~O

Misses []
Use 0 to stop.

Haskell (167,159)
Did this mostly for fun, if anyone's got any suggestions for how to make it shorter, I'd be glad to hear them tho :)
import System.Exit
p x y b|b=x|True=y
main=getContents>>=(return.all (>=0).scanl (\v->p (v-1) (v+1).(==']')) 0.filter (`elem`"[]"))>>=p exitSuccess exitFailure

Edit: Fixed an issue pointed out to me in the comments (added 11 bytes).
Edit 2: Created auxiliary function for testing predicates using guards inspired by user13350, removing 8 bytes.

Fails for ][ (pointed out by user13350)

@user202729 That's an excellent point, that was super careless. Pretty sure it's fixed now.

MATHEMATICA, 88 chars
s = "[ [ my crazy code ] [ don't explode please! [] [ :)Ahh) ]  [] []]]";

r=StringReplace;
StringLength@FixedPoint[r[#,"[]"-> ""]&,r[s,Except@Characters["[]"]-> ""]]

With functions name like RegularExpressionandStringLength` I can never win text code golf context with Mathematica! :)

I know what you mean:) ToCharacterCode is much longer than ord as well... PS: What about setting an exit code?

Length[StringCases[s,"["|"]"]//.{x___,"[","]",y___}:>{x,y}]

Hassium, 104 Bytes
func main(){l=0;r=0;b=input();foreach (c in b){if(c=="[")l++;if(c=="]")r++;}if(!(r==l))exit(1);exit(0);}

Full expanded (note doesn't work in online interpreter as input() is disabled) here

Stax, 14 11 characters
╬Äτ↔EªÉs «Ü

Run and debug it
Credit to @recursive for -3 bytes.
ASCII equivalent:
.[]Y|&{yz|egp!

Remove all characters except [], then remove [] until the string no longer changes. Return 1 if the final string is empty.

Nice.  You can use .[]|& to filter the characters, and then re-use the literal for 11

Pyth, 25 bytes
Ilzv::z"[^[\]]"k"]\[""],[

Try it online!
Python 3 translation:
import re
z=input()
if len(z):
 print(eval(re.sub("]\[","],[",re.sub("[^[\]]","",z))))

Vyxal, 10 bytes
‛[]↔øβ¬[°*

Try it Online!
The joys of having a balanced-bracket digraph.
Explained
‛[]↔øβ¬[°*
‛[]↔       # remove all non "[]" from the input
    øβ¬    # are the brackets unbalanced?
       [°* # if so, multiply the input by the imaginary number `i`. Obviously you can't multiply a string by an imaginary number in python, so this errors.

The thing says 'brainfuck program', so you can safely assume that it doesn't need to remove non-[] chars.

@emanresuA > Please note that Brainfuck programs can have other characters than [], so don't refuse the program just because it has other commands.


text:
Finding n'th character in a Lucky String
Lucky numbers are those numbers which contain only "4" and/or "5". For example 4, 5, 44, 54,55,444 are lucky numbers while 457, 987 ,154 are not.
Lucky number sequence is one in which all lucky numbers exist in increasing order for example       4,5,44,45,54,55,444,445,454,455...
Now we concatenate all the lucky numbers (in ascending order) to make a lucky string     "4544455455444445454455..."
Given n, your task is to find the nth digit of the lucky string. If the digit is 4 then you have to print "F" else you have to print "E".
1<=n<=10^15

Interesting problem, but it is lacking a winning criteria. Please define a winning criteria before not-so-tolerant people close your question (or add a tag that define a clear winning criteria).

Is this code-golf or popularity-contest?

You should provide some test cases

Why does this use 4 and 5 rather than 0 and 1? And why on Earth does it then switch to F and E for the output?

F our and Fiv e, I'm guessing?

JavaScript - 49
for(s=i=0;!(r=s[n+i++]);s+=i.toString(2));"FE"[r]

Execute this on a JavaScript console (tested on Node), with n set to the 1-based index of the digit you want.
Explanation:
The script builds a version of the lucky string, and stops when the character we're looking for exists.
Lucky string:        4 5 44 45 54 55
Generated string: 011011100101110111

The lucky string is equivalent to the concatenation of all binary numbers with the leading one stripped. We can get the index of the appropriate character in s from n by adding the number of leading ones in the string to skip, or, equivalently, how many binary numbers we generated. Luckily for us, we can just grab the current value of i.
It greatly helps to see the final values of s and i after running. For sake of brevity, I won't post a table here, but you can certainly check their values in the console.
Details:
s=i=0

Initializes s and i. s later becomes a string, but rather than initialize to "0", 0 works fine because of implicit type conversion.
i++

Increments i every iteration.
r=s[n+i++]

Gets the character of s at n+i (0 or 1) and stores it in r.
!(r=s[n+i++])

Loops while the character we are looking for is still undefined.
s+=i.toString(2)

Appends the next binary number in sequence to s.
"FE"[r]

Causes the expression to evaluate to F if r is 0, E if r is 1.

amazing! care to give an explanation of why it works? it's very couterintuitive at first sight.

@rewritten Sure, I'll post one in a few minutes. I like to leave my code a mystery for a while.

That's really interesting. I thought about binary, but did not get to the "remove leading '1'" trick. Congratulations!!!

@rewritten I got the idea from OEIS. (I shamelessly search sequences of numbers for problems such as this.)

GolfScript: 48
10 15?,{''+{.52=\53=|}%{&}*},{''++}*=52='F''E'if

Very inefficient.  Can definitely be improved.
Explanation: 10 15?, builds a sequence of the first 10^15 numbers.  The next block preceding the next comma filters the sequence down to so-called lucky numbers by converting to a string, mapping characters of the string to 1 if they equal '4' (52) or '5' (53), and then folding & over the elements.  Finally, fold string concatenation across the lucky sequence to form a big string, take the nth element, and convert to 'F' or 'E' appropriately.

It's not the concatenation of the lucky numbers under 10^15, it's any of the first 10^15 digits of the concatenation of all the lucky numbers. Given that there are 2^n lucky numbers of n digits, it means that to get 10^15 digits you have to get lucky numbers greater than  10^40

But, hey, this is not about speed or feasibility... it's about the least amount of bytes!

GolfScript, 34
Based on Kendall Frey's solution, uses 0-based indices.
~''{0):0 2base(;+.,2$)<}do='FE'1/=

Alternative solution, 44 bytes:
~0{-.0):0.2\?*.@)<}do 1$+0/2base\0%)='FE'1/=

This has the advantage that it's MUCH faster, in fact it's instant even for 15-digit inputs.
Java equivalent (more or less):
public static void f(long n) {
    long k = 0; // number of digits
    long t = 0;
    while (true) {
        k++;
        t = k << k;
        if (t > n) break;
        n -= t;
    }
    // the lucky number with 0s and 1s, prefixed with a 1
    String s = Long.toBinaryString((n + t) / k);
    int d = s.charAt((int) (n % k + 1)) - '0'; // the digit we want
    System.out.println("FE".charAt(d));
}

Haskell, fast
I'm aiming for the fastest program. The hidden structure of this
question, as explained by Kendall Frey, is that the lucky numbers can
be explained as binary numbers. But his answer is searching each
number in succession, making for a terrible runtime for large
numbers. Can we do better? How do we solve for n=10^15 in a speedy
manner?
The length of each lucky number is the following:
x  lucky length
1  4     1
2  5     1
3  44    2
4  45    2
5  54    2
6  55    2
7  444   3
8  445   3
9  454   3
10 455   3
11 544   3
e  t     c

Note the pattern in the length increase. We first have a run of 2
same-length numbers, then 4, 8, 16, 32, ...
I'm going to use this fact to find the length of my number fast, by
multiplying by two until I find the "block" of similar-length numbers,
and accumulate the length up to that block. I then use divison to find
out which number inside that block is the one I'm looking for, and
modulo to find what digit it has.
find n =
  let (digits, n') = block n
      num = n' `div` digits
      digit = digits - (n' `rem` digits) - 1
  in case (num `div` (2^digit)) `rem` 2 of
    0 -> 'F'
    1 -> 'E'

-- Return (digits in each number in block, n-(length up to block)-1)
block n = block' n 2 0 2 1
  where
    block' n add acc pow length
      | acc+add >= n = (length, n-acc-1)
      | otherwise=
        let len' = length+1
            pow' = pow*2
            add' = len'*pow'
        in block' n add' (acc+add) pow' len'

(I stumbled across lots of off-by-one pitfalls while implementing
this. Also, I didn't see aditsus speed-edit until I had already
written this, but at least I bring an explanation :-) )

Python 2.7 based on Kendall Frey somewhat deduction of the problem xD ... well spot
s = "";n=10;i=2
while len(s) < n:
    i+=1; s+=bin(i)[3:]
print "FE"[int(s[n-1])]


text:
Quine...but shifted by one
Referring to the printable ASCII character codes in decimal, we know that from 32 to 126 we have the printable characters with 32 being (space). Your challenge is to write a program using only characters from 32 to 125 (excluding 126) which when executed, prints its own source code except that each character in the source code has its ASCII code increased by one.
For example, if the source code was
main(){printf("Hello World");}

its output would be
nbjo)*|qsjoug)#Ifmmp!Xpsme#*<~

The following are forbidden:

Reading/writing/using any external files or storage (including the internet)
Reading/echoing your own source code
Source codes with fewer than 2 characters (they are no fun). Must be greater than or equal to 2.

Making it a popularity contest where after waiting for at least two weeks, the answer, in any language, with the highest upvotes wins with the smaller character count being the tie-breaker.

Why not allow 126, but it has to go to 32? (I don't know why/how anyone would do this.)

These kinds of questions should also forbid error messages to be considered as "output" (sorry @GariBN). "Output" is stuff deliberately printed on standard output by your code, not arbitrary side effects determined by the language executable.

The inability to use ~ really sucks for GolfScript. Bet you did that on purpose. :-)

define "reading your own source code". Are we allowed to stringify a function, or we have to eval a string instead?

This problem seems not that suitable as a popularity contest.

Python (27 characters)
In the Python shell, the following script will output the desired result:
TzoubyFssps;!jowbmje!tzouby

Yes! it outputs:
SyntaxError: invalid syntax

Oh man, didn't see this coming. :-D

Actually the result is shifted the wrong way :P

@Erbureth This is relevant also for many other answers here... =)

Smart move, although it's not the shortest. xD

I am calling Trollololololol.

huh?, 5 characters
Ntbg

Note that the 5th character is a space after Ntbg.
This is the same trick as in one of my previous answers. Ntbg is an invalid path, so the interpreter will output Ouch! You should run it like this:
huh.exe Ntbg

I can imagine the many quines with "Huh?" now. Reversed Quine: !hcuO Quine: Ouch!

PHP (351)
I'm sure there's a better way to do this, as I am new to codegolfing, but here's my PHP solution:
function q(){$q=chr(39);$a=array('function q(){$q=chr(39);$a=array(',');@$r.=$a[0];foreach($a as$b)$r.=$q.$b.$q.",";$r=substr($r,0,-1);$r.=$a[1];for($i=0;$i<strlen($r);$i++)$r{$i}=chr(ord($r{$i})+1);return $r;}');@$r.=$a[0];foreach($a as$b)$r.=$q.$b.$q.",";$r=substr($r,0,-1);$r.=$a[1];for($i=0;$i<strlen($r);$i++)$r{$i}=chr(ord($r{$i})+1);return $r;}

Output:
gvodujpo!r)*|%r>dis)4:*<%b>bssbz)(gvodujpo!r)*|%r>dis)4:*<%b>bssbz)(-(*<A%s/>%b\1^<gpsfbdi)%b!bt%c*%s/>%r/%c/%r/#-#<%s>tvctus)%s-1-.2*<%s/>%b\2^<gps)%j>1<%j=tusmfo)%s*<%j,,*%s|%j~>dis)pse)%s|%j~*,2*<sfuvso!%s<~(*<A%s/>%b\1^<gpsfbdi)%b!bt%c*%s/>%r/%c/%r/#-#<%s>tvctus)%s-1-.2*<%s/>%b\2^<gps)%j>1<%j=tusmfo)%s*<%j,,*%s|%j~>dis)pse)%s|%j~*,2*<sfuvso!%s<~

GolfScript, 15 chars
{`{)}%"/2+"}.1*

Output:
|a|*~&#03,#~/2+

Try it online.
A fairly straightforward solution based on the technique I used for my entry to the "rotating quine" challenge.  The one tricky detail is that the character ~ (ASCII 126) is disallowed by the challenge rules, so I can't use it to execute my code block.  Fortunately, 1* can be used as a synonym of it.
Explanation:
The code block {`{)}%"/2+"} is duplicated by the ., and the second copy executed by 1* (technically, a one-iteration loop), leaving the other copy on the stack.  Inside the code block, ` stringifies the code block, and {)}% loops over (the ASCII codes of) its characters, incrementing each by one.  Finally, "/2+" pushes the literal string /2+ (which is .1* shifted by one) onto the stack.  At the end of the program, the GolfScript interpreter then automatically prints everything on the stack.
Ps. Yes, I know this is a popularity-contest rather than strict code-golf, but what else am I going to do with GolfScript — ASCII art? ;-)

TI-BASIC, 10
For your TI-83/84 calculator!
DQQ9RXMS@W

Outputs:
ERR:SYNTAX

JavaScript, 117 characters
I know it's not code golf but I golfed it anyway.
function f(){alert((f+';f()').split('').map(function(x){return String.fromCharCode(x.charCodeAt()+1)}).join(''))};f()

(I'm not reading my own source code; I'm simply using the Function object's toString function.)

Java - 1331 bytes, 618 bytes and 504 bytes
Here it is in java. The cool thing is that it is pretty legible and flexible. You may experiment to change the SHIFT variable to 0 and it will be a quine. You may change it to whatever value you want, including negative values and it will shift the code accordingly.
public class Quinex {

    private static final int SHIFT = 1;

    private static String next(String now, boolean mangles) {
        String sb = "";
        for (char c : now.toCharArray()) {
            if (!mangles && c == 87) {
                sb += next(String.valueOf(SHIFT), true);
            } else {
                sb += (char) ((mangles ? c : c == 94 ? 10 : c == 64 ? 34 : c) + SHIFT);
            }
        }
        return sb;
    }

    public static void main(String... args) {
        System.out.println(next(TEXT, false) + next(TEXT, true) + new String(new char[] { 34, 59, 10, 125 }));
    }

    private static final String TEXT = "public class Quinex {^^    private static final int SHIFT = W;^^    private static String next(String now, boolean mangles) {^        String sb = @@;^        for (char c : now.toCharArray()) {^            if (!mangles && c == 87) {^                sb += next(String.valueOf(SHIFT), true);^            } else {^                sb += (char) ((mangles ? c : c == 94 ? 10 : c == 64 ? 34 : c) + SHIFT);^            }^        }^        return sb;^    }^^    public static void main(String... args) {^        System.out.println(next(TEXT, false) + next(TEXT, true) + new String(new char[] { 34, 59, 10, 125 }));^    }^^    private static final String TEXT = @";
}

However, the only drawback in the previous class are the line breaks, which are not permited in the question spec (are outside the range 32 to 125). So I give here a golfed version that is free of line breaks (and free of the quirks to handle them). You may edit the value of the S variable to change the shift. This has 618 bytes:
class Q{static String g(String p,int m){int S=1;String u="";for(char c:p.toCharArray()){if(m==0&&c==87){u+=g(String.valueOf(S),1);}else{u+=(char)((m>0?c:c==64?34:c)+S);}}return u;}public static void main(String[]y){System.out.println(g(T,0)+g(T,1)+new String(new char[]{34,59,125}));}static final String T="class Q{static String g(String p,int m){int S=W;String u=@@;for(char c:p.toCharArray()){if(m==0&&c==87){u+=g(String.valueOf(S),1);}else{u+=(char)((m>0?c:c==64?34:c)+S);}}return u;}public static void main(String[]y){System.out.println(g(T,0)+g(T,1)+new String(new char[]{34,59,125}));}static final String T=@";}

Surely, if we drop the fine adjustment of the offset and hardcode the value of the shift, we can do a completely golfed version with 504 bytes:
class Q{static String g(String p,int m){String u="";for(char c:p.toCharArray()){u+=(char)((m>0?c:c==64?34:c)+1);}return u;}public static void main(String[]y){System.out.println(g(T,0)+g(T,1)+new String(new char[]{34,59,125}));}static final String T="class Q{static String g(String p,int m){String u=@@;for(char c:p.toCharArray()){u+=(char)((m>0?c:c==64?34:c)+1);}return u;}public static void main(String[]y){System.out.println(g(T,0)+g(T,1)+new String(new char[]{34,59,125}));}static final String T=@";}

Perl 5, 284 characters include the linefeeds
Not being allowed to use ~ made it a bit more tricky.
#!/usr/bin/perl
$_=<<X;
#!/usr/bin/perl
Y
\$a=\$_;
s/\\\\/\\\\\\\\/g;
s/\\\$/\\\\\\\$/g;
\$b=\$_;
\$_=\$a;
s/Y/\\\$\\_\\=\\<\\<X\\;\\n\${b}X/;
s/(.)/chr(ord(\$1)+1)/ge;
print;
X
$a=$_;
s/\\/\\\\/g;
s/\$/\\\$/g;
$b=$_;
$_=$a;
s/Y/\$\_\=\<\<X\;\n${b}X/;
s/(.)/chr(ord($1)+1)/ge;
print;

Python, 99
s='import sys;sys.stdout.write("".join(chr(ord(c)+1)for c in a%(s,a)))';a='s=%r;a=%r;exec s';exec s

Output:
t>(jnqpsu!tzt<tzt/tuepvu/xsjuf)##/kpjo)dis)pse)d*,2*gps!d!jo!b&)t-b***(<b>(t>&s<b>&s<fyfd!t(<fyfd!t

This can be shortened to 75 chars, but it will print a new line character after the output, technically breaking the rules:
s='print"".join(chr(ord(c)+1)for c in a%(s,a))';a='s=%r;a=%r;exec s';exec s

Why don't you just put a tab (\x09) at the end, since a tab shifted by one is a new line (\x0A). Then your shortened version would work with 76 bytes.

Stax, 16 bytes
"{^m'#bL"{^m'#bL

Run and debug it
Adaption of the "34bL"34bL quine. Since now " becomes # which does not need to be escaped we can just include it in the string.

Lua - 192
Pretty straightforward,
s=[[print((('s=['..'['..s..']'..']'..s):gsub('.',function(x)return string.char(x:byte()+1)end)))]]print((('s=['..'['..s..']'..'];'..s):gsub('.',function(x)return string.char(x:byte()+1)end)))

C - 156
char*f="char*f=%c%s%c,q[200];i;main(){sprintf(q,f,34,f,34);while(q[i])q[i++]++;puts(q);}",q[200];i;main(){sprintf(q,f,34,f,34);while(q[i])q[i++]++;puts(q);}

Just the classic C quine with required modifications
P.S, apparently sprintf(f,...,f,...) is a segfault.

JavaScript (276)
Without using .toString():
function q(){x=String.fromCharCode;y=x(39);a=['function q(){x=String.fromCharCode;y=x(39);a=[','];r=a[0]+y+a[0]+y+","+y+a[1]+y+a[1];q="";for(c in r)q+=x(r[c].charCodeAt(0)+1);return q;}'];r=a[0]+y+a[0]+y+","+y+a[1]+y+a[1];q="";for(c in r)q+=x(r[c].charCodeAt(0)+1);return q;}

Ruby, 63
Darn, can't use a heredoc on this one.
s="s=%p;(s%%s).chars{|c|$><<c.succ}";(s%s).chars{|c|$><<c.succ}

Ruby has a native method .succ that does this on a character, and printing without a newline is shorter than printing with, so this works out pretty neatly.

C, 153
main(a){char b[999];sprintf(b,a="main(a){char b[999];printf(a=%c%s%c,34,a,34);for(a=0;b[a];)b[a++]++;puts(b);}",34,a,34);for(a=0;b[a];)b[a++]++;puts(b);}

Another modification of the classic quine in c...

><>, 16 bytes
" r:2+l?!;1+o50.

Try it here!
This is more-or-less just a standard quine in ><> (without using the g instruction). The only differences are it doesn't read its own source-code and increments each character by 1 before outputting it.
Outputs
#!s;3,m@"<2,p61/

*><>, 15 bytes (non-competing)
" r:2+Ol?!;1+ou

Try it here!

11 bytes

Haskell, 64 bytes
main=putStr$succ<$>s++show s;s="main=putStr$succ<$>s++show s;s="

Try it online!

Perl 5, 55 bytes
$_=q{print chr(1+ord)for split//,"\$_=q{$_};eval"};eval

Try it online!

Tcl, 89 bytes
puts [join [lmap c [split [read [open $argv0]] ""] {format %c [expr [scan $c %c]+1]}] ""]

Try it online!

Tcl, 89 bytes
puts [join [lmap c [split [read [open $argv0]] ""] {scan $c %c s;format %c [incr s]}] ""]

Try it online!

Two approaches; the same byte length!

J, 42 Bytes
(>:&.(u:inv)@,quote)'(>:&.(u:inv)@,quote)'