3 ms·
I spent an entire day trying to decipher how to replace spaces with tabs. Wish I had been better with regular expressions.
by kelukelugames 12y ago
I spent an entire day trying to decipher how to replace spaces with tabs. Wish I had been better with regular expressions.
- gknoy 12y agoI hope this isn't flippant, but have you read the Perl regex man pages [0]? "Perl compatible" regexes are very common, and are explained _really_ well. Similarly, the Perl Cookbook (from O'Reilly) has a whole chapter on regular expressions -- even crazy ones like detecting US phone numbers (hard!) -- with explanations. That chapter is QUITE good, and I highly recommend it even you don't write Perl. For your specific problem at hand, I assume you want to replace spaces with a tab character. In Perl, you could do: # replace four spaces with a tab, globally $line =~ s/ /\t/g; You can do this directly on the command line as well: perl -e 'while (<>) { $line = $_; $line =~ s/ /\t/g; print $line; }' < foo_spaces.py > foo_tabs.py I have a gist [1] which has very slightly more comments, if you prefer. To paraphrase XKCD, there are now N+1 regex explanations, and I apologize that mine is comparatively worse than all of them. :) 0: http://perldoc.perl.org/perlre.html http://perldoc.perl.org/perlre.html 1: https://gist.github.com/gknoy/94c382299c4543f2e863 https://gist.github.com/gknoy/94c382299c4543f2e863
- kelukelugames 12y agoThanks for sharing the man page link. I am reading it now! :)
- deleted 12y ago[deleted]
- japhyr 12y agoHave you looked at sed yet?
- kelukelugames 12y agoSed was the problem. On Mac the syntax is slightly different and it doesn't take \t as tab. Those two curve balls took some extra research. I didn't actually take the entire day. :)