调用带有参数 (vars) 的 awk shebang 脚本
我有一个这样定义的 awk 脚本:
#!/usr/bin/env awk
BEGIN { if (!len) len = 1; end = start + len }
{ for (i = start; i < end; i++) { print $1 } }
我已将其保存为 columns
并对其进行 chmod +x
处理。我想调用它,以便在遍历文件时定义 start
和 end
。我以为这应该有效:
cat some_file | columns -v start=2
但事实并非如此。帮助!
I have an awk script that I have defined thus:
#!/usr/bin/env awk
BEGIN { if (!len) len = 1; end = start + len }
{ for (i = start; i < end; i++) { print $1 } }
I have saved it as columns
and chmod +x
'd it. I want invoke it so that start
and end
are defined as it traverses over a file. I was thinking this should work:
cat some_file | columns -v start=2
But it doesn't. Help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试使用:
作为口译员
Try using:
as an interpreter
env 是处理这个问题的最简单方法:
添加更多选项,并确保不会干扰您的参数和 awk 的参数:
由于 env 有 POSIX 标准,这个 shbang 应该可以帮助您解决跨非标准 shbang 实现的困难unixen。
编辑
写完这篇文章后我意识到'-S'是一个不符合POSIX的FreeBSD环境扩展。因此,外壳包装可能是可行的方法,尽管不幸的是。
env is the easiest way to handle this problem:
to add more options, and to ensure no interference with your arguments, and awk's arguments:
as env has a POSIX standard, this shbang should get you around the difficulties of non-standard shbang implementations across unixen.
EDIT
after having written this I realized that '-S' is a non-POSIX compliant FreeBSD env extension. So shell wrapper is probably the way to go, unfortunate as that is.
不幸的是,这并不容易以可移植的方式解决。标准技术如下所示(用
/usr/bin/awk
替换您的 awk 路径):硬编码
awk
路径和非标准-f< /code> 标志,使得它不能在所有 *nix 上移植。如果您只打算在一台计算机上运行脚本,那么这可能会很好地工作。但是,要制作可移植的 awk 脚本,您需要将其包装在 shell 脚本中。您可以通过以下两种方法在一个文件中执行此操作:
第一种方法是标准且易于阅读:
不幸的是,这在两个关键方面存在不足:
'
字符,则您需要像这样输入:'"'"'
来“转义”它。另一个解决方案是使用
sed
去除sh
包装器:这类似于两行 shabang 标头。它使用第 3 行以下的文件作为脚本参数来调用 awk。这使您可以保持漂亮的语法突出显示,并且仍然可以随心所欲地使用
'
字符。我看到的两个缺点是:Unfortunately, this is not easy to solve in a portable way. The standard technique looks like this (substitute
/usr/bin/awk
for your awk path):The hard-coded
awk
path and non-standard-f
flag, makes this not portable across all *nixes. If you are only ever going to run your script on one machine, then this may work fine. However, to make a portableawk
script, you will need to wrap it in a shell script. Here are two ways that you can do it in one file:The first way is standard and easy to read:
Unfortunately, this falls short in two key ways:
'
character, you will need to type it like this:'"'"'
to "escape" it.Another solution, is to use
sed
to strip out thesh
wrapper:This is something like a two line shabang header. It calls awk using the file from line 3 down as the script argument. This allows you to keep your pretty syntax highlighting and you can still use
'
characters to your heart's content. The two downsides I see are:下面是这个问题的答案——
Below is the answer for this problem -