如何从管道和文件中输入awk输入? [英] How to feed awk input from both pipe and file?

查看:455
本文介绍了如何从管道和文件中输入awk输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何从管道输出和文件中获取awk来获取字符串?

I was wondering how do I get awk to take a string from the pipe output and a file?

我基本上有一连串的命令,这些命令最终会吐出一个字符串.我想针对一个csv文件(用逗号分隔的列)检查此字符串.然后,我要在文件中找到包含csv文件第7列中的字符串的第一行,并打印出该行第5列的内容.另外,我不太了解linux命令行实用程序/awk,因此请随意提出完全不同的方法. :)

I've basically have a chain of commands that eventually will spit out a string. I want to check this string against a csv file (columns separated by commas). Then, I want to find the first row in the file that contains the string in the 7th column of the csv file and print out the contents of the 5th column of that line. Also, I don't know linux command line utilities/awk too well, so feel free to suggest completely different methods. :)

CSV文件内容如下:

CSV file contents look like this:

col1,col2,col3,col4,col5,etc...
col1,col2,col3,col4,col5,etc...
etc...

我的一般思路:

(rest of commands that will give a string) | awk -F ',' 'if($5 == string){print $7;exit}' filename.txt

可以做到吗?如果是这样,我如何告诉awk与该字符串进行比较? 我发现了一些有关在文件名前使用-符号和ARGV[]的内容,但无法使其正常工作.

Can this be done? If so, how do I tell awk to compare against that string? I've found some stuff about using a - symbol with ARGV[] before the filename, but couldn't get it working.

推荐答案

正如Karoly建议的那样,

As Karoly suggests,

str=$( rest of commands that will give a string )
awk -v s="$str" -F, '$7==s {print $5; exit}' file

如果要使用管道喂awk:

If you want to feed awk with a pipe:

cmds | awk -F, 'NR==FNR {str=$0; next}; $7==str {print $5}' - file

我认为第一种选择更具可读性.

I think the first option is more readable.

这篇关于如何从管道和文件中输入awk输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆