Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to write a powershell function that wraps a sed/perl/etc command
    primarykey
    data
    text
    <p>I have a number of sed/perl/etc "one-liner" commands that I use frequently:</p> <ul> <li><code>head -1</code> (Print the first line of a file)</li> <li><code>sed $d</code> (Drop the last line of a file)</li> <li><code>perl -pe '$_ = qq($. $_)'</code> (Number lines in a file)</li> </ul> <p>You get the idea.</p> <p>All of these commands have the same behaviour - they can take input from standard input, or work on a series of files whose names are passed as arguments. I'd like to wrap these common scripts up as Powershell functions, so that I don't have to remember the exact syntax to use. However, aliases don't work like that, and if I do the "obvious" approach with functions:</p> <pre><code>function numlines { perl -pe '$_ = qq($. $_)' $args } </code></pre> <p>it works with files as arguments (<code>numlines my_file.pl</code>) but not with input from a pipe (<code>cat my_file.pl | numlines</code>).</p> <p>Is there a way to write the function so that it works both ways?</p> <p>To clarify - I can use bat files to do this. For example, numlines.bat containing</p> <pre><code>@perl -pe "$_ = qq($. $_)" %* </code></pre> <p>but having to invoke cmd.exe and the general ugliness of bat files (that "Terminate batch job (Y/N)?" prompt when you hit CTRL-C :-() makes me wish for a similarly simple solution within Powershell...</p> <hr> <p>Based on Richard's suggestion below, I tried:</p> <pre><code>function test { [CmdletBinding()] param( [Parameter(mandatory=$true, ValueFromPipeline=$true)] $data ) process { perl -pe '$_ = qq($. $_)' } } </code></pre> <p>If I then do <code>test file.txt</code> (which I'd want to run effectively identically to <code>perl -pe '$_ = qq($. $_)' file.txt</code>) the function runs, but waits for data on standard input rather than processing <code>file.txt</code>. The same thing happens when I try <code>cat file.txt | test</code> - which I'd expect to act identically to <code>cat file.txt | perl -pe '$_ = qq($. $_)'</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload