awk command to find average of a column from a file - php

I have written an awk command to read from a log file and get the average of a specific column.
The command is :
awk '{sum += $NF} END {print sum/NR}' /serach_grater500ms_test.txt
Everything is working fine on terminal but when I try to execute this command in php script as follow :
$no_of_request=exec("awk '{sum += $NF} END {print sum/NR}' /serach_grater500ms_test.txt");
print_r($no_of_request);
It throw me a syntax error
PHP Notice: Undefined variable: NF in /home/javed/Downloads/read_log.php on line 11
awk: line 1: syntax error at or near }
How can I solve it ?

If you want to pass a string into a shell script, you need to quote it properly for the shell. The easiest way to do this is to make it a single-quoted literal; this requires transforming the single quotes inside the string.
exec('awk \'{sum += $NF} END {print sum/NR}\' /serach_grater500ms_test.txt');

In your example the php string is between double-quote ". The character ' inside has no special meaning, you dont need to escape it. On the other hand the $ (like in sum += $NF) is interpreted, so the php replaces $NF with its value (empty!).
With Inian's answer the php string is between single-quote '. So the php does not look for variable inside ($NF is protected); but you have to escape further \' inside.
You can also have it work with the double-quote of your example; but you escape only the \$ of $NF :
$no_of_request=exec("awk '{sum += \$NF} END {print sum/NR}' filee");

Related

PHP CLI get *raw* commandline

Is it possible to get the exact raw command line in PHP as typed in?
$ ./example.php --key1="value" --key2='value' --key3= value-with-leading-double-blank
I'd like to now if value was enclosed in single or double quotes and if any blanks were typed. Obviously implode(' ', $argv[]) does not work as surrounding quotes and blanks have been stripped already.
Any hints?

How insert an XML in a command line [duplicate]

I got one error while passing the arguments to outlook_DataParsing.sh:
$ sh outlook_DataParsing.sh delete node doc('/opt/ws40/contacts.xml')//Directory/Contacts/Contact[#id='22222']
and I am reading all the arguments as:
str=$#
The error is following:
-bash: syntax error near unexpected token `('
Can anybody help me?
There are a number of "special" characters in a shell command, including $()[]
Most of these can simply be passed by enclosing the parameter in double quotes
foo "(hello)[]"
This however will not fix the $ sign, as it is intended for variables. You can instead use single quotes to pass a $ sign
foo '$im_not_a_variable'
If all else fails, ANY character can be escaped with a backslash \ including a space (no quotes needed)
foo \(hello\)\[\]\ \$im_not_a_variable

Php and unix grep backslashing does not work

I have a fairly simple problem I just cannot seem to find a solution. I want to delete a line containing a certain string in all the files in a directory on my website. This string contains double quotes though. I have been trying to find a solution using backslashing but its does not work.
The string I want to replace is:session_register("c$key");
I'm using this php and unix code:
$command = "sed -i '/session_register(\"c$key\")/d;' ./*";
$output = shell_exec($command);
I want to delete this line because session_register is outdated.
It does not do anything but does not give me an error. What is the problem or how should I backslash?
Thanks a lot!
You need to double escape $ as well since $ is special regex symbol means end of input. Also use single quote instead of double for your $command string assignment.
Try this:
$command = 'sed -i.bak \'/session_register("c\\$key")/d;\' ./*';
$output = shell_exec($command);

How can execute php scripts in bash?

I need parse uri in shell scripts. So, I tried to use php in bash as below.
#!/bin/sh
uri="http://www.google.com?key=value
key="host"
value=$(php -r "$parse = parse_url('$uri'); echo $parse['$key']")
It has showing the following error.
PHP Parse error: syntax error, unexpected '=' in Command line code on line 1
Some body can help how to use embedded php in bash ?
A cheap way of debugging this is to use echo to see what you're passing in to php:
echo "$parse = parse_url('$uri'); echo $parse['$key']"
shows
= parse_url('http://www.google.com?key=value'); echo ['host']
You're already using $uri to mean "the value of the shell variable uri", so it's not surprising that $parse is also considered a shell variable and expanded to its value (unset, nothing).
Use \$ when you want a literal dollar sign in your double quoted string:
value=$(php -r "\$parse = parse_url('$uri'); echo \$parse['$key']")
You can use it easily, but you must be careful because of escaping in bash.
I recommend to use single quotes (you do not need to escape anything) and exit from the quotes when you want to do something special. Your example:
php -r '$parse=parse_url("'$url'"); echo $parse["'$part'"];'
Note that
you do not need to escapes $parse
you need to exit from single quotes when inserting bash variable: '$url'
you cannot use single quotes in the single quotes! do use double quotes " instead.
Update:
Just for the clarification - parse error happened because $parse was interpreted as bash variable (empty string) so the php command incorrectly started with =.

PHP exec() with double quote argument

I've been having trouble running a command using PHP's exec() function on Windows. Per a comment on PHP's site on exec():
In Windows, exec() issues an internal call to "cmd /c your_command".
My command looks like:
"path\to\program.exe" -flag1 attribute1 -flag2 attribute2 -flag3 "attribute3 attribute4"
Under regular execution of this command in my local command prompt, without the /c flag, the command runs fine. However, with the introduction of the /c flag, command prompt tells me that "The system cannot find the path specified."
I think the command prompt is interpreting the double-quoted argument as a path to another file, but that's the furthest I've gotten with this problem.
Does anybody have any ideas on how to get past this? Thanks!
I also encountered this issue, and the cause of it is, indeed, the internal use of "cmd /c" as described in your own answer.
I have done some investigation, and have found that this was resolved in PHP 5.3, which is why some commenters were unable to reproduce it.
It was fixed in the following commit:
https://github.com/php/php-src/commit/19322fc782af429938da8d3b421c0807cf1b848a#diff-15f2d3ef68f383a87cce668765721041R221
For anyone who still needs to support PHP 5.2, it is fairly easy to replicate the fix in your own code. Instead of:
$cmd = "...any shell command, maybe with multiple quotes...";
exec($cmd);
use
function safe_exec($cmd, &$output = null, &$result_code = null) {
if (strtoupper(substr(php_uname('s'), 0, 3)) == "WIN"
&& version_compare(PHP_VERSION, "5.3", "<"))
{
$cmd = '"' . $cmd . '"';
}
return exec($cmd, $output, $result_code);
}
$cmd = "...any shell command, maybe with multiple quotes...";
safe_exec($cmd);
This replicates the behaviour of PHP 5.3 and above, in the same way as in the above-linked commit.
Note that this applies to all shell commands, not just exec() as used in my example.
I've figured out the answer by myself...
After perusing cmd.exe's /? and trying to decipher that, I've noticed one important section:
If all of the following conditions are met, then quote characters on the command line are preserved:
No /S switch (Strip quotes)
Exactly two quote characters
No special characters between the two quote characters, where special is one of: & < >( ) # ^ |
There are one or more whitespace characters between the the two quote characters
The string between the two quote characters is the name of an executable file.
Otherwise, old behavior is to see if the first character is a quote character and if so, strip the leading character and remove the last quote character on the command line, preserving any text after the last quote character. To negate this behaviour use a double set of quotes "" at the start and end of the command line.
It seems as though if there more than one pair of quotes at any time, quotation marks will be stripped from the second pair of quotes and on.
A relevant question: How do I deal with quote characters when using cmd.exe but not completely relevant, since PHP will not allow you to modify its exec() command by putting an /S flag on its call (which would definitely be a lot easier).
I've managed to work around this problem by directly changing directories with chdir() to the folder where the .exe is located, then chdir()'ing back to my original working directory. It's an extremely hacky solution, given the case that I'm lucky that I only have one set of arguments using double quotes. If anybody were to have multiple arguments using double quotes, I wouldn't know how to solve that...
Just a guess (I am not familiar with PHP on windows): maybe escape the quotes as " becoming ""?
"path\to\program.exe" -flag1 attribute1 -flag2 attribute2 -flag3 ""attribute3 attribute4""
Whatever the solution is, make sure that when there's some form of user-input that gets passed to this command as arguments that you use escapeshellarg and/or escapeshellcmd.
I hope it will help
escapeshellarg() — Escape a string to be used as a shell argument
escapeshellcmd() — Escape shell metacharacters

Categories