I'm translating a csh script to bash an came across a line that looks like
@ lines = `grep num_lines ../config.txt | awk '{printf("%d",int(2ドル))}' `
What does the '@' do here? I found some documentation stating that csh uses '@' for expressions. However, this looks like a normal variable assignment to me. When I run the grep and awk part of the code in bash the output is an integer with a preceding '%d', e.g. '%d 12045'.
1 Answer 1
Well, it’s impossible to know what the author of that script was thinking. But here are some observations:
- If the
awk
command, indeed, saysprintf
, then it is printing the integer value of the second string on the input line. - As roaima commented, and as I have been known to comment,
awk
is a very powerful program. You almost never need to run it in combination withgrep
,sed
, or anotherawk
. Sogrep num_lines filename | awk '{ printf("%d", int(2ドル)) }'
can be writtenawk '/num_lines/ { printf("%d", int(2ドル)) }' filename
- As I mentioned above,
int(2ドル)
gives you the integer part of the second string on the input line. So, if the config file saysnum_lines foo
, you will get0
. If it saysnum_lines 3.14
, you will get3
. It seems unlikely that you would need to take such precautions with a well-formed configuration file. - In any case,
printf("%d", int(2ドル))
is overkill. As far as I can tell,printf("%d", 2ドル)
andprint int(2ドル)
are (almost) exactly equivalent. - The one difference that I can identify
is that the
printf
version doesn’t write a newline at the end:$ echo "num_lines 42" | awk '{printf("%d", 2ドル)}'; date 42Mon, May 13, 2019 12:00:00 AM $ echo "num_lines 42" | awk '{print int(2ドル)}'; date 42 Mon, May 13, 2019 12:00:01 AM
but this isn’t really relevant, since`...`
strips off a trailing newline. - You say "this looks like a normal variable assignment to me".
But users of [t]csh know that it doesn’t allow
variable=value
you have to sayset variable=value
or@ variable=expr
Of course a simple integer constant is a validexpr
, so the author may simply be using@
instead ofset
because it’s shorter and they know that the value is an integer.
So the statement is setting the lines
variable
to the value of num_lines
from ../config.txt
.
-
Thanks for the comprehensive answer! I did not know this convenient way to look for specific strings with awk.
lines=$( awk '/num_lines/ {print int(2ドル)}' ../config.txt )
works perfect (in bash).Loibologic– Loibologic2019年05月13日 12:25:41 +00:00Commented May 13, 2019 at 12:25
awk
command saysprint
and notprintf
?Ambiguous
error. (orExpression Syntax
intcsh
).grep
. Uselines=$(awk '/num_lines/ {print 2ドル}' ../config.txt)
or evenlines=$(awk '1ドル=="num_lines" {print 2ドル}' ../config.txt)