使用 awk 的结果作为参数来 grep 一个文件?

grep a file using results from awk as parameter?

我有 2 个文件:

1 - userfile.txt 格式=> bob:bobhash
2 - passfile.txt 格式=> bobhash:bobpass

我想通过给定的用户 "bob" 获得 bobpass,如果可能的话,在单行命令中。

到目前为止,我是这样做的:

awk -F: '="bob" {print }' userfile.txt
# output: bobhash 
# copy by using mouse

cat passfile.txt | grep 'bobhash' | awk -F: '{print }'
#output: bobpass

我想知道是否有更好的方法来做到这一点。我已经尝试过 grep -f,但没有成功。

这是您已有内容的修改版本,可能会满足您的需求。

简单的一行:

cat passfile.txt | grep "$(awk -v user="bob" -F: '=user {print }' userfile.txt)" | awk -F: '{print }'

修改为在脚本中使用:

my_user="bob"

cat passfile.txt | grep "$(awk -v user="${my_user}" -F: '=user {print }' userfile.txt)" | awk -F: '{print }'

第二个选项增加了将用户作为变量传递的能力,而不是对其进行硬编码。如果您在脚本中使用它,可以动态设置它,使其更加灵活。

另一种仅使用 awk 的解决方案:

awk -F: -v user="$(awk -F: '="bob" {print }' userfile.txt)" '=user {print }' passfile.txt

运行 awk一次:

awk -v search=bob -F: 'NR==FNR && ==search {hash= };
    NR>FNR && ==hash {print "pw="  }'  userfile.txt passfile.txt

当找不到匹配项(或两次)时,您可以为某些控件更改此设置。

使用以下单行 awk方法:

awk -F: 'NR == FNR{ if(=="bob") p=; next}(p == ){print }' userfile.txt passfile.txt

这里我们处理两个文件。
工作原理:

$ awk 'NR == FNR { # some actions; next} # other condition {# other actions}' file1.txt file2.txt

When processing more than one file, awk reads each file sequentially, one after another, in the order they are specified on the command line. The special variable NR stores the total number of input records read so far, regardless of how many files have been read. The value of NR starts at 1 and always increases until the program terminates. Another variable, FNR, stores the number of records read from the current file being processed. The value of FNR starts at 1, increases until the end of the current file is reached, then is set again to 1 as soon as the first line of the next file is read, and so on. So, the condition NR == FNR is only true while awk is reading the first file. Thus, in the program above, the actions indicated by # some actions are executed when awk is reading the first file; the actions indicated by # other actions are executed when awk is reading the second file, if the condition in # other condition is met. The next at the end of the first action block is needed to prevent the condition in # other condition from being evaluated, and the actions in # other actions from being executed, while awk is reading the first file.

以防万一,这是一个全局解决方案,它将 userfile.txt 中的所有用户与其在 passfile.txt

中的相应密码匹配
awk -F":" 'NR==FNR{a[]=;next}a[]{print a[],}' users pass