As you use pipes on the command line, I guess you will like the command line switches -e, -p and -n: They allow you to write a short perl program on the commandline, right into your pipes.

Here are three short solutions for your question. They differ in that the first one prints a final space at the end of the results while the other solutions don't:

xcommand|perl -wne '/(\S+)/ and print "$1 "' xcommand|perl -we 'print join " ", map{/(\S+)/; $1} <>' xcommand|perl -we 'print join " ", map{(split" ", $_)[0]}<>'

Let's explain the tools we used in these three solutions:

The -w switch does the bulk of the work: It tells me when I did something wrong.

The -n switch in the first example builds a loop around our main program to process the input line by line: while(<>){ ... the code goes here ... }.

The -e switch reads the next command line argument and executes it as the perl program.

In the first solution, the program simply says /(\S+)/;: "Search {//} for at one or more {+} non-white-space characters {\S} and remember them all {()}". print "$1 ": print what you have remembered and a space. You remember, this is done for every line of the input.

The second solution does almost the same thing. Instead of the -n switch, we use map the list of all input lines <> and join the results by spaces. Thus, we do not print an extra space after the last field.

The third solution uses the split function instead of a regular expression.

Note: In a Dos-Window (UUUHHHH-OOOOHHH-EEEEEKS), the examples will not work as given because there the "shell" messes the quotation marks up. You have to use ouble quotes (") around your code (and you can't use them inside)!


In reply to RE: Help for awk/regex/newbie by Yaakov
in thread Help for awk/regex/newbie by cmenser

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.