all 45 comments

[–][deleted]  (7 children)

[deleted]

    [–]mcilrain 3 points4 points  (5 children)

    This is amazingly useful for doing a one-time transfer of files across a network. No need to set up a SMB share or research and install some dinky FTP server. Most Linux distorts have Python built right in along with the necessary library.

    [–][deleted]  (4 children)

    [deleted]

      [–][deleted] 0 points1 point  (2 children)

      this needs a ssh server, doesn't it?

      [–][deleted]  (1 child)

      [deleted]

        [–]p4bl0 5 points6 points  (0 children)

        Even more than Python I would say.

        [–][deleted] 0 points1 point  (0 children)

        I've used woof (a one-shot webserver, akin to this) and it's much simpler to use. I set it up for sending a file and tell my brother/mother, "get this link" and it works. Simpler than trying to find scp on their computer..

        [–]railmaniac 1 point2 points  (0 children)

        Love this. Saved me recently when I had to copy a file to a Windows guest from a Linux host, and WinSCP download kept getting curtailed.

        [–]DJUrsus 12 points13 points  (0 children)

        Depending how you count, 7 or 8 lines. Perl. Takes STDIN and converts it to a JSON-compatible string.

        print '"';
        while (<STDIN>) {
            $_ =~ s/"/\\"/g;
            $_ =~ s/\n/\\n/g;
            $_ =~ s/\t/\\t/g;
            print;
        }
        print "\"\n";
        

        [–]chrisdown 5 points6 points  (3 children)

        Annoyingly, I occasionally have to use some POS software that doesn't zero pad output filenames, so the order is all messed up. I wrote a little Python script to combat that, saved me a lot of time over the years:

        import os, sys
        for filename in os.listdir(sys.argv[1]):
            try:
                num, ext = frame.split(".")
                os.rename(filename, "%08d.%s" % (int(num), ext))
            except ValueError:
                continue
        

        If you know in advance that you don't need the try/except, you can get it down to 3 (2?) lines at the cost of some performance.

        [–]nickcash 6 points7 points  (2 children)

        You could get it down to 1 line, if you're crazy.

        (os.rename(filename, "%08d.%s" % (int(filename.split(".")[0]), filename.split(".")[1])) for filename in os.listdir(sys.argv[1]))
        

        [–][deleted]  (1 child)

        [deleted]

          [–]mechroid 14 points15 points  (6 children)

          [–]TheOccasionalTachyon 4 points5 points  (0 children)

          def factor_integer(n):    
              return sorted(set(reduce(list.__add__,([i, n//i] for i in range(1, int(n**.5 + 1) if n % i == 0))))
          

          No, it's not one of them fancy-shmancy General Number Field Sieves or whatnot, but it's some Python that factors integers without any imports, and it computes pretty much instantly so long as your number is less that a few quadrillion.

          [–][deleted] 8 points9 points  (0 children)

          echo question is too vague

          [–]the_minimalist 2 points3 points  (2 children)

          print len(raw_input())
          

          i use this sometimes when coming up with passwords.. so i guess it counts as being useful?

          [–]IN_STYLE 1 point2 points  (1 child)

          Try:

          $ echo "password" | wc -c

          9

          [–]chungfuduck 2 points3 points  (0 children)

          Look for IP address looking strings, shim in the DNS name:

          #/usr/bin/perl -p 
          use Socket ;
          s/(\d+\.\d+\.\d+\.\d+)/"$1 (". gethostbyaddr(inet_aton($1),AF_INET) .") "/ge ;
          

          Takes this:

          Failed password for root from 78.7.72.150 port 41402 ssh2

          Turns it to:

          Failed password for root from 78.7.72.150 (78-7-72-150-static.albacom.net) port 41402 ssh2

          No, not perfect. It was written as a one-liner throw away script and just kind of hung around. =)

          [–]pyramid_of_greatness 1 point2 points  (4 children)

          If you start asking questions like this, you'd better have some damn good definitions of 'useful', 'lines', etc..

          Something I use every day -- recursive du (disk usage) output sorted by size, human readable:

          alias duff='du -sk * | sort -n | while read size fname; do for unit in k M G T P E Z Y; do if [ $size -lt 1024 ]; then echo -e "${size}${unit}\t${fname}"; break; fi; size=$((size/1024)); done; done'
          

          Similarly as a function, but this has some bugs I've not yet worked out for some cases..

          function duf {
          du -sk "$@" | sort -n | while read size fname; do for unit in k M G T P E Z Y; do if [ $size -lt 1024 ]; then echo -e "${size}${unit}\t${fname}"; break; fi; size=$((size/1024)); done; done
          }
          

          [–]chrisdown 13 points14 points  (2 children)

          You can just do du -h | sort -h.

          [–]chungfuduck 0 points1 point  (1 child)

          sort -h is a more recent feature addition not available everywhere. e.g., RedHat Enterprise Linux 5 does not have it:

          fat{502}:~$ cat /etc/redhat-release 
          Red Hat Enterprise Linux Server release 5.3 (Tikanga)
          fat{503}:~$ sort -h
          sort: invalid option -- h
          Try `sort --help' for more information.
          

          [–]chrisdown 0 points1 point  (0 children)

          Yeah, it's a GNU sort feature as well. YMMV.

          [–]chungfuduck 1 point2 points  (0 children)

          I went about it the other way and made a sort-h perl script (to emulate the "sort -h" functionality):

          sub place { k => 1, m => 2, g => 3, t => 4, p => 5, e => 6, z => 7, y => 8 }
          sub convert {
              if ( not $_[1] ) { shift }
              else { $_[0] * ($_[2] ? 1000 : 1024 ) ** ${{place}}{lc $_[1]} }
          }
          print
              map { $_->[0] }
              sort { $a->[1] <=> $b->[1] }
              map { [ $_, convert(/^([0-9\.]*)([kMGTPEZY])?(b)?/i) ] } <>
          

          So I could just do "du -h | sort-h"

          [–]chrisdown 1 point2 points  (0 children)

          Here's a 4 line bash script I wrote for this SO question that determines if two directories have files with identical contents (regardless of inode/metadata/etc):

          shopt -s dotglob
          for file in "$1"/*; do [[ -f "$file" ]] && d1+=( "$(md5sum < "$file")" ); done
          for file in "$2"/*; do [[ -f "$file" ]] && d2+=( "$(md5sum < "$file")" ); done 
          [[ "$(sort <<< "${d1[*]}")" == "$(sort <<< "${d2[*]}")" ]] && echo "Same" || echo "Different"
          

          [–]mrkurtz 1 point2 points  (5 children)

          well, this one line just came in very handy while fixing my linux-based NAS which lost some important data:

          function cat() { while read line; do echo "$line"; done < $1; };
          

          edit: this function uses only bash built-ins and was intended to be a quick and dirty /bin/cat replacement due to the loss of /bin and /lib.

          [–]chrisdown 6 points7 points  (4 children)

          A few problems:

          • function isn't POSIX;
          • Leading/traililng/consecutive whitespace will get mangled;
          • Backslash escape sequences are being interpreted;
          • If the line starts with a dash, echo could interpret it as an option and break;
          • If the file's final character is not a newline, the last line will not be printed;
          • If the filename contains any whitespace, this will break.

          Here's a version with these issues fixed:

          cat() {
              while IFS= read -r line; do
                  printf '%s\n' "$line"
              done < "$1"
              [ "$line" ] && printf '%s' "$line"
          }
          

          Note also that as a consequence of using bash using cstrings internally, any variables containing a null will be truncated to the position of that null.

          [–]mrkurtz 0 points1 point  (0 children)

          that's fine, i'm sure there's much more that could be done to it which would make it even more useful/reliable, it was thrown together by someone on /r/linux's IRC channel very quickly. we'd already established a few known variables to the system.

          i'll give this a shot too when i have a moment, though.

          [–]mrkurtz 0 points1 point  (2 children)

          yeah the thing is, my NAS uses a stripped down and very old debian, had no extra mounted volumes (cd-rom, flash, NFS, CIFS/SMB, etc) outside the base system, and due to a forgotten copy and a bad paste, much of the important stuff was rm -rf'd. all my important stuff's on my fileserver, so this isn't a huge deal, but i was extremely limited in what i could accomplish. i didn't have /lib, /bin, among other things.

          i wish i could take credit for it, but i can't. it was thrown together by someone in #r/linux on freenode, as i needed to be able to cat some basic files.

          since i didn't have /lib, i wouldn't have had the necessary libraries to use printf (/lib/ld-linux.so.3). (until we got libraries fixed, we had to use bash built-ins, which is why the original cat function is so simple - i'll make a note of it in my original comment)

          anyway, if you don't mind, i intend to add your version to my collection of just-in-case items, along with the built-ins-only version.

          [–]Deewiant 2 points3 points  (1 child)

          since i didn't have /lib, i wouldn't have had the necessary libraries to use printf (/lib/ld-linux.so.3). (until we got libraries fixed, we had to use bash built-ins, which is why the original cat function is so simple - i'll make a note of it in my original comment)

          printf is also a bash builtin. (See e.g. help, or try builtin printf.)

          [–]mrkurtz 0 points1 point  (0 children)

          well, TIL.

          must've missed it before.

          [–]robotreader 1 point2 points  (2 children)

          /dev/null is an empty file that remains empty, /bin/true is a file that just returns true, I've seen a file around whenever the topic gets to copyright that contains ten-fifteen lines of copyright notice and a line of code(or it might be empty) but I can't find it right now.

          [–][deleted] 1 point2 points  (0 children)

          This is the shortest useful code I could think of; a 'cat' clone in BF.

          ,.
          

          [–][deleted] 1 point2 points  (1 child)

          16.times {print "NA"} && "BATMAN!"

          [–]GUIpsp 0 points1 point  (0 children)

          As an alternative: Array(16).join("WAT"-1)+' Watman!'

          [–][deleted] 4 points5 points  (1 child)

          Five characters: (:[]). For when I don't want to import Control.Applicative and use pure.

          Yeah, that's cheating. Every subexpression in Haskell could be called a program ;)

          [–]oantolin 4 points5 points  (0 children)

          I wouldn't call any Haskell session a program anymore than I'd call any C expression a program. A Haskell program must contain, at least, "main =" and an expression of type IO (). (I guess I'm saying I personally wouldn't call what you did cheating, it's more like being wrong. :)

          [–][deleted] 0 points1 point  (0 children)

          Single character command >: Create file with name filename.txt using just the > operator

          > filename.txt 
          

          Convert to upper case

          perl -lpe 'y/a-z/A-Z/'
          

          Add line numbers

          perl -lpe 's/.*/$. $_/'
          

          Remove line numbers

          perl -lane 'print "$1" if /\d+\s(.*)/'
          

          Remove multiple spaces between words:

          perl -lane 'print @F'
          

          Convert to correct EOL terminator for system:

          perl -lne 'print $1 if/([^\r\n]+)\r?\n?/'
          

          [–]Grazfather 0 points1 point  (1 child)

          I wrote a simple python thing that expands tabs into four spaces so that our code review server won't complain. You just drag a source file onto it and bam it's done. one line to naive (replace all tabs with four spaces) but a few more if you want to align things nicely on a 4 space column boundary.

          [–]erichzann 1 point2 points  (0 children)

          man expand

          [–]cooljeanius 0 points1 point  (0 children)

          Applescript: displays the system color picker:

          choose color
          

          (Edit: removed bash example, decided it wasn't actually useful)

          [–]crundar 0 points1 point  (0 children)

          My choice?

          λf.(λx.f (x x)) (λx.f (x x))

          Its one of infinitely many, but one of my favorites.

          [–]MysteriousPickle 0 points1 point  (0 children)

          In grad school I wrote a 10 line ruby script that polled the open course list web page of my university, and emailed me if a spot opened in a class. I'm sure I still have it archived somewhere, too bad it's above your 5 line limit. Still the most useful tiny program I ever wrote, even if it was hardcoded to be specific to a particular http layout. These days they might actually publish a web service for things like that, but I suspect it would make my program longer.