TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Using Ruby instead of sed and awk

3 pointsby nithinbekalover 10 years ago

2 comments

Moyamoover 10 years ago
Even though, the ruby one-liner seems more legible, it is a lot longer (and probably a lot slower).<p>In this case I don&#x27;t see what&#x27;s wrong with the sed, awk or grep commands (fast and short).<p>To explain how they work<p><pre><code> sed -i &#x27;&#x2F;^$&#x2F;d&#x27; input.txt # for every line matching &#x27;^$&#x27; (empty line) apply &#x27;d&#x27; (delete the line). grep -v &#x27;^$&#x27; # print every line not matching &#x27;^$&#x27; (empty line) awk &#x27;NF&#x27; input.txt # &#x27;NF&#x27; stand for Number of Fields (this is equivalent to number of columns # in a table). If the number of fields is 0 the line must be empty. In awk # 0 is false and non-zero is true. Thus when &#x27;NF&#x27; is non-zero (non-empty) # it is true, and the line will be printed.</code></pre>
jonathonfover 10 years ago
Instead of:<p><pre><code> cat foo.txt | ruby -ne &#x27;BEGIN{ $x=[]}; $x &lt;&lt; $_.chomp; END { puts $x.sort }&#x27; </code></pre> just use `sort`:<p><pre><code> sort foo.txt </code></pre> There&#x27;s a reason these commands already exist. :)