问题
I'm issuing gawk command from Windows CMD but it just stuck there.Same command is working perfectly fine in Cygwin Terminal. I am trying to find first occurrence of ending brace "}" on first column in a file after line number 30
Command is
gawk 'NR > 30 && /^}$/ { print NR; exit }' Filename.c > Output.txt
I noticed another thing that when i issue command form CMD,Besides sticking it creates a file with the name of Line number(If above command is executed then 30 is created)
回答1:
The command line
gawk 'NR > 30 && /^}$/ { print NR; exit }' Filename.c > Output.txt
is not interpreted by Windows command interpreter as expected because of two reasons:
A straight single quote has no special meaning on Windows command line in comparison to Unix and Linux shells. Therefore the string within the two straight single quotes is not interpreted as single parameter string like in shells on Unix/Linux.
The parameter string for
gawk
contains several characters with special meaning in Windows command processes:>
... the redirection operator
See the Microsoft TechNet article Using command redirection operators for details on this operator.&&
... conditional command concatenation operator
See the answer on Single line with multiple commands using Windows batch file for details on this operator.^
... character to use for escaping operators like>
and&
for being interpreted as literal character on command execution.
On opening a command prompt window and running cmd /?
, the brief help of Windows command interpreter is output on several pages. The last paragraph on last help page lists on which characters in a directory/file name or another string requires enclosing the name/string in straight double quotes.
So the standard solution for Windows command line would be using
gawk.exe "NR > 30 && /^}$/ { print NR; exit }" Filename.c > Output.txt
But this also does not produce the expected result. I think, but does not know it for sure, that gawk
is ported from Unix/Linux to Windows without adapting the interpretation of straight single and double quotes.
For that reason another solutions is needed which is using straight single quotes and escaping each special character in gawk
parameter string to be interpreted as literal character by Windows command interpreter.
gawk.exe 'NR ^> 30 ^&^& /^^}$/ { print NR; exit }' Filename.c > Output.txt
This command line makes the Unix/Linux console application gawk
with a parameter string being unusual for Windows also work within a Windows command process.
回答2:
Standard advice to avoid Windows quoting hell is to store the awk script (in this case NR > 30 && /^}$/ { print NR; exit }
) in a file (e.g. named script.awk
) and execute it as awk -f script.awk Filename.c > Output.txt
.
来源:https://stackoverflow.com/questions/38170509/gawk-command-in-cmd-with-operator-not-working