linux - 如何在 Bash 脚本中将字符串作为参数传递给 AWK

标签 linux bash unix awk

我有一个要过滤的文本文件 使用 awk。文本文件如下所示:

foo 1
bar 2
bar 0.3
bar 100
qux 1033

我想在 bash 脚本中使用 awk 过滤这些文件。

#!/bin/bash

#input file
input=myfile.txt

# I need to pass this as parameter
# cos later I want to make it more general like
# coltype=$1
col1type="foo"   

#Filters
awk '$2>0 && $1==$col1type' $input

但不知何故失败了。正确的做法是什么?

最佳答案

使用 awk-v 选项传递它。这样,您就可以分离出 awk 变量和 shell 变量。它也更整洁,没有额外的引用。

#!/bin/bash

#input file
input=myfile.txt

# I need to pass this as parameter
# cos later I want to make it more general like
# coltype=$1
col1type="foo"   

#Filters
awk -vcoltype="$col1type" '$2>0 && $1==col1type' $input

关于linux - 如何在 Bash 脚本中将字符串作为参数传递给 AWK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2451635/

相关文章:

Windows 上的 Java/MongoDB 消息长度错误,但 Linux 上没有

linux - 获取 "-("和 ")-"之间的字符串,linux 目录

linux - 在 mac 终端中过滤文件

shell - 如何知道给定用户是否对给定路径具有读和/或写权限

linux - SDL 2.0.1 Linux Make编译错误

linux - 在 Node.js 中跟踪命名管道

c++ - 等到用户在 C++ 中按下 Enter 键?

php - 在 OSX 上读取 p12 证书时写入权限错误 (OSStatus -61)

linux - shell脚本这行代码是什么意思

linux - sed 在文件中搜索带有特殊字符的字符串