Reputation: 303
First, is it possible to run an awk in PHP? I am trying to print the second column of an output that is stored in a variable. If this is not possible,
$f=foo.txt
$o=file($f);
$len=count($o);
$rnum= rand(2,$len);
echo $o[$rnum];
exec(awk -v '{ print $2}', $output); // This obviously isn't right, but is there a way to make this logic work?
echo $output;
An example of one line of output from $o[$rnum] would be : 12 20 dog, in which I would like to only get "dog" and store it in a variable
Upvotes: 1
Views: 865
Reputation: 3820
The previous respondent is correct about explode. Here is the sample data file I devised:
my foo.txt:
12 20 dog
13 21 cat
14 22 fish
15 23 bear
16 24 lion
and here's a PHP script that does what you want:
<?php
$f="./foo.txt";
$o = file($f);
$len = count($o);
$rnum = mt_rand(0,$len-1);
echo "Random record: ",$o[$rnum],"<br>\n";
$data = trim($o[$rnum]);
list($n,$m,$animal) = explode("\t",$data);
echo "Just the animal: ",$animal;
You need quotes around the file name with PHP incidentally. Also, mt_rand is supposed to produce a more random result. My data file is delimited with tabs.
Hope this helps.
p.s. I would not recommend using calls like system or exec b/c there are security risks associated with these two functions. Usually there is a way to do things in PHP without having to resort to a system call.
Upvotes: 1
Reputation: 532
You are looking for explode()
If you actually need to execute a command in shell you can use system()
http://php.net/manual/en/function.explode.php
Upvotes: 1