Penguin
Note: You are viewing an old revision of this page. View the current version.

Many oneliners rely on the magic of Perl's -i switch, which means when files supplied on the commandline are opened they are edited in place, and if an extension was passed, a backup copy with that extension will be made. -e specifies the Perl code to run. See perlrun(1) for any other switches used here - in particular, -n and -p make powerful allies for -i.

The unsurpassed power of Perl's RegularExpression flavour contributes a great deal to the usefulness of nearly every oneliner, so you will also want to read the perlretut(1) and perlre(1) manpages to learn about it.

Removing empty lines from a file

perl -ni.bak -e'/\S/ && print' file1 file2

In Shell
for FILE in file1 file2 ; do mv "$F"{,.bak} ; sed '/^ *$/d' < "$F.bak" > "$F" ; done

Collapse consecutive blank lines to a single one

perl -00 -pi.bak -e1 file1 file2

Note the use of 1 as a no-op piece of Perl code. In this case, the -00 and -p switches already do all the work, so only a dummy needs to be supplied.

Binary dump of a string

perl -e 'printf "%08b\n", $_ for unpack "C*", shift' 'My String'

Replace literal "\n" and "\t" in a file with newlines and tabs

cat $file | perl -ne 's/\\n/\012/g; s/\\t/\011/g; print'

This has a useless use of cat, and uses -n but then does an explicit print. You also don't need to use octal-coded character codes. It should be rewritten as
perl -pe 's!\\n!\n!g; s!\\t!\t!g' $file

You can use any punctuation as the separator in an s/// command, and if you have backslashes or even need literal slashes in your pattern then doing this can increase clarity.

List all currently running processes

perl -pe 'BEGIN {undef$/;chdir"/proc";@ARGV=sort{$a<=>$b}glob("*/cmdline")}

$ARGV=/(\d+)/;print "$1\t";s@\0@ @g;$_.="\n";'

This prints the process ID and command line of every running process on the system (except some "special" kernel processes that lie about/don't have command lines). You might want such a command if you suspect a rootkit or something similar has been installed, and you can't trust your "ps" binary.

Basically, this runs a loop over all the files in /proc/*/cmdline, printing the content of those files (after printing the leading digits in the filename, and replacing null characters with a space). "$/" is a special variable used for the end-of-line marker, and it needs to be unset so that even the empty/unreadable files still cause the loop to print out the filename. The -p switch for perl means do the loop, using the input of the rest of the arguments (assumed to be filenames). We cheat and manually assign @ARGV in the BEGIN{..} block. Also, we need to tell sort to use a numeric comparison (<=>) instead of the default string comparison.


AddToMe