Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Assuming '<code>identify filename</code>' is itself a command, then I think you'll need to use Perl for this. In the best Perl inscrutable style:</p> <pre><code>while (&lt;&gt;) { s/#(\w+)#/my $x = qx%identify $1%; chomp $x; $x/e; print; } </code></pre> <p>This reads a line of input ('<code>&lt;&gt;</code>') into the implicit variable '<code>$_</code>'; the next line applies a substitute operation to the implicit variable - more details in a moment - and then the '<code>print</code>' prints the implicit variable.</p> <p>As to the substitute operation '<code>s///</code>', the first part looks for a hash '#', a series of one or more 'word' characters - alphanumerics or underscore - and another hash, making the identified file name available as '<code>$1</code>'. The second part is the replacement string. After the third slash is the modifier '<code>e</code>' which means 'execute the replacement as bit of Perl'. And the relevant bit of Perl is:</p> <pre><code>my $x = qx%identify $1%; chomp $x; $x </code></pre> <p>The first part executes the command '<code>identify filename</code>' if the string between the hash marks is 'filename', saving the output, newline and all, in local variable $x. The '<code>chomp</code>' operation removes the newline; the final '<code>$x</code>' yields a value - the string that was output by the 'identify' command. (Somewhat to my surprise, Perl does not allow a simpler looking: <code>s/#(\w+)#/chomp qx%identify $1%/e</code>; the error was '<code>Can't modify quoted execution (``, qx) in chomp at xx.pl line 3, near "qx%identify $1%)"</code>'.)</p> <p>Consider the 'identify' command:</p> <pre><code>echo "identified file $1 as $PWD/$1" </code></pre> <p>Now consider the input line:</p> <pre><code>abc#def#ghi </code></pre> <p>The output is:</p> <pre><code>abcidentified file def as /Users/jleffler/tmp/soq/defghi </code></pre> <p>(where <code>/Users/jleffler/tmp/soq</code> happened to be my current directory while running the command).</p> <p>Rather less inscrutably:</p> <pre><code>while (my $line = &lt;&gt;) { if ($line =~ m/#(\w+)#/) { my $identity = qx{identify $1}; chomp $identity; $line =~ s/#\w+#/$identity/; } print $line; } </code></pre> <p>Certainly not as compact, but the explanation is very similar.</p> <p>Note that the initial edition is not the most compact form possible. Consider this version:</p> <pre><code>perl -p -e 's/#(\w+)#/my $x = qx%identify $1%; chomp $x; $x/e' </code></pre> <p>The '-p' option places the script (the argument to '-e') in a read, execute, print loop (REPL).</p> <p>That's one of the wonders of Perl - TMTOWTDI (pronounced 'tim-toady') - There's More Than One Way To Do It.</p>
 

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