不包含字符串的生产线和匹配线以下的输出线

时间:2016-09-23 06:20:27

标签: linux bash unix awk grep

我很清楚我可以在这里做些什么,使用grep -v '^--'grep -A 1,但我想我可能需要使用awk来匹配。

我的数据如下:

Random text line 1
--Data1
Random text line 2
--Data2
Random text line 3  
--Data3
Random text line 4  
--Data4
Random text line 5  
--Data5

问题是,我需要运行一个命令 - 让我们在不以' - '开头的所有行上调用它command1并捕获输出以及它下面的行。

所以我想要组合的三个命令是:

grep -v '^--' file.txt | command1 > text-output

grep -A 1 [not sure] > --data-below-text

我可以通过将变量存储在while read line; do类型的命令中然后存储和回显变量来实现。但是,我觉得可能有一种更简单的方法可以更有效地获得以下内容:

Random text line 1, text-output, --Data1
Random text line 2, text-output, --Data2
Random text line 3, text-output, --Data3
Random text line 4, text-output, --Data4
Random text line 5, text-output, --Data5

当然,如果使用变量是唯一的方法,我也愿意这样做。我只是想确保,因为我知道如果我决定在路上并行使用代码,变量会变得有点冒险。任何方向都非常感谢。

2 个答案:

答案 0 :(得分:1)

这是一种方式:

command_wrapper(){
  in=$(cat -)
  one=$(echo "$in" | head -n1)
  two=$(echo "$in" | tail -n1)
  result=$(echo "$one" | command1)
  echo "$one, $result, $two"
}

grep -A1 -v '^--' file.txt | command_wrapper

这是另一种方式:

textlines=$(grep -v '^--' file.txt)
results=$(echo "$textlines" | command1)
datalines=$(grep '^--' file.txt)
paste <(echo "$textlines") <(echo "$results") <(echo "$datalines") |
  tr '\t' ',' > output.txt

答案 1 :(得分:0)

这是awk的一种方式,可以做你以后的事情。

$ cat yourcommand 
echo "printing : $@"

:~/test/awk$ awk '!/^--/ { cmd = "./yourcommand "$0 ; cmd | getline outvar ; print outvar  } /^--/ { print }' 1
printing : Random text line 1
--Data1
printing : Random text line 2
--Data2
printing : Random text line 3
--Data3
printing : Random text line 4
--Data4
printing : Random text line 5
--Data5

我们匹配所有不以 - 开头的行,并将该行的输出传递给&#39; ./ yourcommand&#39; - 在我的情况下,只是预先打印&#39;打印:&#39;到了这一行 - 但你应该可以用自己的输入命令替换。

awks getline然后将输出存储在outvar中,然后我们将其打印出来。以 - 开头的行正常打印。

编辑:getline只获取下一行。如果你有更多的线要提取,让我知道,我应该能够让它给你剩下的。

相关问题