简体   繁体   English

如何打印管道第一部分的结果?

[英]How to print the result of the first part of the pipe?

I have the following grep: 我有以下grep:

grep -Po '(?<=PROGRAM\()[^\)]+(?=\))' /home/programs/hello_word.sh 

Wich displays the string between PROGRAM( and ) : Wich显示PROGRAM()之间的字符串:

RECTONTER

Then, I need to know if these string extracted is contained in a file, so: 然后,我需要知道这些提取的字符串是否包含在文件中,因此:

grep -Po '(?<=PROGRAM\()[^\)]+(?=\))' /home/programs/hello_word.sh | xargs -I % grep -e % /home/leherad/pgm_currentdate

File content: 档案内容:

RECTONTER
CORASFE
RENTOASD
UBICARP

If its found, returns the line of /home/leherad/pgm_currentdate, but I want to print the line extracted in the first grep ( RECTONTER ). 如果找到它,则返回/ home / leherad / pgm_currentdate的行,但是我想打印在第一个grep( RECTONTER )中提取的行。 If not found, then wouldn't return nothing. 如果找不到,则不会返回任何内容。

There is a simple way to do this, or I should not complicate and would be better build a script and save the first grep in a variable? 有一种简单的方法可以执行此操作,否则我不应该复杂化,而是更好地构建脚本并将第一个grep保存在变量中?

You can store it on a variable first: 您可以先将其存储在变量中:

read -r FIRST < <(exec grep -Po '(?<=PROGRAM\()[^\)]+(?=\))' /home/programs/hello_word.sh) && grep -e "$FIRST" /home/leherad/pgm_currentdate

Update 01 更新01

#!/bin/bash
shopt -s nullglob
for FILE in /home/programs/*; do
    read -r FIRST < <(exec grep -Po '(?<=PROGRAM\()[^\)]+(?=\))' "$FILE") && grep -e "$FIRST" /home/leherad/pgm_currentdate && echo "$FIRST"
done

I think a straightforward way to solve this is to use a function. 我认为解决此问题的直接方法是使用函数。

Also, your grep pattern will match shell comments, which could cause unexpected behavior in your xargs command when there are more than one matches; 另外,您的grep模式将匹配shell注释,当存在多个匹配项时,这可能会在xargs命令中导致意外行为; you might want to take steps to only grab the first match. 您可能想采取一些步骤,只抢第一场比赛。 It's hard to say without actually seeing the input files, so I'm guessing this is either ok or comments are actually the expected place for your target pattern. 在没有实际看到输入文件的情况下很难说,所以我猜测这是可以的,或者注释实际上是目标模式的预期位置。

Anyway, here's my best guess at a function that would work for you. 无论如何,这是对您可以使用的功能的最佳猜测。

get_program() {
  local filename="$1"
  local program="$( grep -m1 -Po '(?<=PROGRAM\()[^\)]+(?=\))' "$filename" )"
  if grep -q -e "$program" /home/leherad/pgm_currentdate; then
    echo $program
    grep -e "$program" /home/leherad/pgm_currentdate
  fi
}

get_program /home/programs/hello_word.sh

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM