Penguin
Diff: PerlOneLiners
EditPageHistoryDiffInfoLikePages

Differences between version 11 and predecessor to the previous major change of PerlOneLiners.

Other diffs: Previous Revision, Previous Author, or view the Annotated Edit History

Newer page: version 11 Last edited on Tuesday, December 16, 2003 5:33:40 pm by JohnMcPherson Revert
Older page: version 2 Last edited on Wednesday, August 27, 2003 12:57:40 pm by PhilMurray Revert
@@ -1,12 +1,31 @@
-__Removing empty lines from a file __ 
+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 __.  
  
- perl -ni .bak -e 'print if /\S/' file1 file2  
+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
  
-;-i :means perl will edit the file in place and save a backup with the .bak extension  
-;-e :means execute the code/command in the quotes  
-;-n :read the manpage perlrun(1) for this one  
+!! Removing empty lines from a file  
  
-The command will loop through the files you specify and print out the lines (into the file you specified) if they match the RegularExpression /\S/ 
+ 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 perl -n (for no print) and then does an explicit print.) This could be rewritten as:  
+ perl -pe 's@\\n@\012@g; s@\\t@\011@g' < $file  
+(you can use any punctuation as the separator in an s/// command, and if you have \ chars in your regexp then doing this can increase clarity.)  
+----  
  
 AddToMe