SYS-CON MEDIA Authors: Liz McMillan, Yeshim Deniz, Elizabeth White, William Schmarzo, Dana Gardner

Blog Feed Post

Unix To PowerShell - Wc

PowerShell_unix PowerShell is definitely gaining momentum in the windows scripting world but I still hear folks wanting to rely on unix based tools to get their job done.  In this series of posts I’m going to look at converting some of the more popular Unix based tools to PowerShell.

wc

The Unix “wc” (word count) command will print the character, word, and newline counts for each file specified and a total line if more than one file is specified.  This command is useful for quickly scanning a directory for small and large files or to quickly look at a file and determine it’s relative size.  The Get-Content Cmdlet will return the number of characters in the full but not the number of lines and words.  The following script will emulate the behavior of the Unix “wc” command with a few changes in the way parameters are supplied.

   1: #----------------------------------------------------------------
   2: # Wc.ps1
   3: #----------------------------------------------------------------
   4: param
   5: (
   6:   [string]$filespec = $null,
   7:   [bool]$lines = $false,
   8:   [bool]$words = $false,
   9:   [bool]$chars = $false,
  10:   [bool]$longest = $false
  11: );
  12:  
  13: #----------------------------------------------------------------
  14: # function New-Stat
  15: #----------------------------------------------------------------
  16: function New-Stat()
  17: {
  18:   param([string]$name);
  19:   $stat = "" | select Lines, Words, Chars, Longest, Name;
  20:   $stat.Lines = $stat.Words = $stat.Chars = $stat.Longest = 0;
  21:   $stat.Name = $name;
  22:   $stat;
  23: }
  24:  
  25: #----------------------------------------------------------------
  26: # function Get-ColumnList
  27: #----------------------------------------------------------------
  28: function Get-ColumnList
  29: {
  30:   param
  31:   (
  32:     [bool]$lines = $false,
  33:     [bool]$words = $false,
  34:     [bool]$chars = $false,
  35:     [bool]$longest = $false
  36:   );
  37:   $cols = $null;
  38:   if ( $lines ) { $cols += @("Lines"); }
  39:   if ( $words ) { $cols += @("Words"); }
  40:   if ( $chars ) { $cols += @("Chars"); }
  41:   if ( $longest ) { $cols += @("Longest"); }
  42:   $cols += @("Name");
  43:   
  44:   $cols;
  45: }
  46:  
  47: #----------------------------------------------------------------
  48: # function Do-Wc
  49: #----------------------------------------------------------------
  50: function Do-Wc()
  51: {
  52:   param
  53:   (
  54:     [string]$filespec = $null,
  55:     [bool]$lines = $false,
  56:     [bool]$words = $false,
  57:     [bool]$chars = $false,
  58:     [bool]$longest = $false
  59:   );
  60:   
  61:   # if no options are given, set them all to true
  62:   if ( !$lines -and !$words -and !$chars -and !$longest )
  63:   {
  64:     $lines = $words = $chars = $longest = $true;
  65:   }
  66:   
  67:   $stats = $null;
  68:   
  69:   $stat_total = New-Stat -name "total";
  70:   
  71:   [System.IO.FileInfo[]]$files = Get-ChildItem $filespec -ErrorAction SilentlyContinue;
  72:   if ( $null -ne $files )
  73:   {
  74:     foreach ($file in $files)
  75:     {
  76:       # new stat object for current file
  77:       $stat = New-Stat -name $file.Name;
  78:       
  79:       [string[]]$content = Get-Content $file;
  80:       
  81:       # wc only prints newlines so the last line is omitted
  82:       $stat.Lines = $content.Length -1;
  83:       
  84:       # iterate through the lines in the file
  85:       for ($i=0; $i -lt $content.Length; $i++)
  86:       {
  87:         $info = $content[$i] | Measure-Object -word -line -char
  88:         $stat.Words += $info.Words;
  89:         $stat.Chars += $info.Characters;
  90:         if ( $info.Characters -gt $stat.Longest ) { $stat.Longest = $info.Characters }
  91:         
  92:         # increment the count for newline characters (except for last line)
  93:         if ( $i -lt ($content.Length-1) ) { $stat.Chars += 2; }
  94:       }
  95:       
  96:       $stat_total.Chars += $stat.Chars;
  97:       $stat_total.Lines += $stat.Lines;
  98:       $stat_total.Words += $stat.Words;
  99:       
 100:       $stats += @($stat);
 101:     }
 102:     $stats += @($stat_total);
 103:  
 104:     $stats | select (Get-ColumnList -lines $lines -words $words -chars $chars -longest $longest) | ft -AutoSize;
 105:   }
 106:   else
 107:   {
 108:     "No files matching pattern '$filespec' found!";
 109:   }
 110: }
 111:  
 112: Do-Wc -filespec $filespec -lines $lines -words $words -chars $chars -longest $longest;

*Update – Thanks to twitter user @Jaykus for the tips on the Measure-Object cmdlet.  Although it didn’t offer a complete replacement, it did make the script faster than the character iteration for each line.

*Update 2 – Added support for longest line count as well.

Read the original blog entry...

More Stories By Joe Pruitt

Joe Pruitt is a Principal Strategic Architect at F5 Networks working with Network and Software Architects to allow them to build network intelligence into their applications.

Latest Stories
Serveless Architectures brings the ability to independently scale, deploy and heal based on workloads and move away from monolithic designs. From the front-end, middle-ware and back-end layers, serverless workloads potentially have a larger security risk surface due to the many moving pieces. This talk will focus on key areas to consider for securing end to end, from dev to prod. We will discuss patterns for end to end TLS, session management, scaling to absorb attacks and mitigation techniques.
Crosscode Panoptics Automated Enterprise Architecture Software. Application Discovery and Dependency Mapping. Automatically generate a powerful enterprise-wide map of your organization's IT assets down to the code level. Enterprise Impact Assessment. Automatically analyze the impact, to every asset in the enterprise down to the code level. Automated IT Governance Software. Create rules and alerts based on code level insights, including security issues, to automate governance. Enterpr...
Eric Taylor, a former hacker, reveals what he's learned about cybersecurity. Taylor's life as a hacker began when he was just 12 years old and playing video games at home. Russian hackers are notorious for their hacking skills, but one American says he hacked a Russian cyber gang at just 15 years old. The government eventually caught up with Taylor and he pleaded guilty to posting the personal information on the internet, among other charges. Eric Taylor, who went by the nickname Cosmo...
Most modern computer languages embed a lot of metadata in their application. We show how this goldmine of data from a runtime environment like production or staging can be used to increase profits. Adi conceptualized the Crosscode platform after spending over 25 years working for large enterprise companies like HP, Cisco, IBM, UHG and personally experiencing the challenges that prevent companies from quickly making changes to their technology, due to the complexity of their enterprise. An accomp...
The benefits of automated cloud deployments for speed, reliability and security are undeniable. The cornerstone of this approach, immutable deployment, promotes the idea of continuously rolling safe, stable images instead of trying to keep up with managing a fixed pool of virtual or physical machines. In this talk, we'll explore the immutable infrastructure pattern and how to use continuous deployment and continuous integration (CI/CD) process to build and manage server images for any platfo...
DevOpsSUMMIT at CloudEXPO, to be held June 25-26, 2019 at the Santa Clara Convention Center in Santa Clara, CA – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real results. Am...
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
It cannot be overseen or regulated by any one administrator, like a government or bank. Currently, there is no government regulation on them which also means there is no government safeguards over them. Although many are looking at Bitcoin to put money into, it would be wise to proceed with caution. Regular central banks are watching it and deciding whether or not to make them illegal (Criminalize them) and therefore make them worthless and eliminate them as competition. ICOs (Initial Coin Offer...
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
The current environment of Continuous Disruption requires companies to transform how they work and how they engineer their products. Transformations are notoriously hard to execute, yet many companies have succeeded. What can we learn from them? Can we produce a blueprint for a transformation? This presentation will cover several distinct approaches that companies take to achieve transformation. Each approach utilizes different levers and comes with its own advantages, tradeoffs, costs, risks, a...
Organize your corporate travel faster, at lower cost. Hotailors is a next-gen AI-powered travel platform. What is Hotailors? Hotailors is a platform for organising business travels that grants access to the best real-time offers from 2.000.000+ hotels and 700+ airlines in the whole world. Thanks to our solution you can plan, book & expense business trips in less than 5 minutes. Accordingly to your travel policy, budget limits and cashless for your employees. With our reporting, int...
This sixteen (16) hour course provides an introduction to DevOps, the cultural and professional movement that stresses communication, collaboration, integration and automation in order to improve the flow of work between software developers and IT operations professionals. Improved workflows will result in an improved ability to design, develop, deploy and operate software and services faster.
Enterprises are universally struggling to understand where the new tools and methodologies of DevOps fit into their organizations, and are universally making the same mistakes. These mistakes are not unavoidable, and in fact, avoiding them gifts an organization with sustained competitive advantage, just like it did for Japanese Manufacturing Post WWII.
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...