在 shell 脚本中使用 gawk

发布于 2024-08-05 02:12:23 字数 137 浏览 5 评论 0原文

我想做一些类似的事情:

for i in 1 2 3
do
   gawk '{if ($i==$2) {print $0;}}' filename
done

这可能吗?

谢谢

I want to do something of the sort:

for i in 1 2 3
do
   gawk '{if ($i==$2) {print $0;}}' filename
done

is this possible?

thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

晨曦÷微暖 2024-08-12 02:12:23

为了避免丑陋的引用,您可以使用 gawk 的变量传递功能:

for i in 1 2 3
do
    gawk -v param=$i '{if (param==$2) {print $0}}' filename
done

In order to avoid ugly quoting, you can use gawk's variable passing feature:

for i in 1 2 3
do
    gawk -v param=$i '{if (param==$2) {print $0}}' filename
done
一抹淡然 2024-08-12 02:12:23

假设您想要 gawk 脚本,

{if ($1 == $2 ) ... }
{if ($2 == $2 ) ... }
{if ($3 == $2 ) ... }

您可以执行以下操作:

for i in 1 2 3
do
   gawk '{if (
$i'==$2) {print $0;}}' filename
done

Assuming that you want the gawk script to be

{if ($1 == $2 ) ... }
{if ($2 == $2 ) ... }
{if ($3 == $2 ) ... }

you can do:

for i in 1 2 3
do
   gawk '{if (
$i'==$2) {print $0;}}' filename
done
知你几分 2024-08-12 02:12:23

我想到了对脚本的两种可能的解释:

  1. 您确实想要搜索“1”、“2”,然后搜索“3”作为 filename 中的第二个字段
  2. 您实际上想要搜索第一个 shell 脚本参数,然后是第二个,...

以下是循环的两个版本:

for i in 1 2 3; do 
   gawk "{if (\"$i\"==\$2) {print \$0;}}" filename
done
for i in "$@"; do
   gawk "{if (\"$i\"==\$2) {print \$0;}}" filename
done

Two possible interpretations of your script come to mind:

  1. You really do want to search for "1", "2", and then "3" as the second field in filename
  2. You actually want to search for the 1'st shell script parameter, then the second, ...

Here are both versions of the loop:

for i in 1 2 3; do 
   gawk "{if (\"$i\"==\$2) {print \$0;}}" filename
done
for i in "$@"; do
   gawk "{if (\"$i\"==\$2) {print \$0;}}" filename
done
浮云落日 2024-08-12 02:12:23

当然,这是可能的,但它可能不会做你想做的事。

...想一想,您想要它做什么?从你写的内容来看还不是很清楚。您可能需要更改的一件事是用双引号替换单引号,因为变量(如 $i)不会替换为单引号字符串。

Well sure, it's possible, but it probably won't do what you want it to do.

...come to think of it, what do you want it to do? It's not really clear from what you've written. One thing you'll probably have to change is to replace the single quotes with double quotes because variables (like $i) aren't substituted into single-quoted strings.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文