在“grep”结果中包含标题

问题描述 投票:0回答:8

有没有一种方法可以将“head -1”和“grep”命令组合成一个目录中的所有文件,并将输出重定向到输出文件。我可以使用“sed”来完成此操作,但它似乎不如 grep 快。

sed -n '1p;/6330162/p' infile*.txt > outfile.txt

使用 grep 我可以一次执行以下一个文件:

head -1 infile1.txt;  grep -i '6330162' infile1.txt > outfile.txt

但是,我需要对目录中的所有文件执行此操作。插入通配符没有帮助,因为它首先打印标题,然后打印 grep 输出。

shell grep
8个回答
49
投票

下面的意思是你只需要输入一次命令(而不是使用 && 并输入两次),它也很容易理解。

some-command | { head -1; grep some-stuff; }

例如

ps -ef | { head -1; grep python; }

更新:这似乎只适用于

ps
,抱歉,但我想这通常是人们想要的。

如果您希望它适用于任意命令,似乎您必须编写一个迷你脚本,例如:

#!/bin/bash

first_line=true

while read -r line; do
    if [ "${first_line}" = "true" ]; then
        echo "$line"
        first_line=false
    fi
    echo "$line" | grep $*
done

我将其命名为

hgrep.sh
。然后你就可以这样使用:

ps -ef | ./hgrep.sh -i chrome

这种方法的好处是我们使用

grep
,因此所有标志的工作方式完全相同。


20
投票

这将通过使用单个接收命令来工作:

some-command | sed -n '1p;/PATTERN/p'

将其与多行标题一起使用也很容易:

$ sudo netstat --tcp --udp --listening --numeric --program | sed --quiet '1,2p;/ssh/p'
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1258/sshd           
tcp6       0      0 :::22                   :::*                    LISTEN      1258/sshd           

重申,@samthebest 的解决方案仅适用于非常特定的情况;这适用于任何写入标准输出的命令。


3
投票
for file in * do [ "$file" = outfile.txt ] && continue head -n 1 "$file" grep -i '...' "$file" done > outfile.txt
    

2
投票
我会这么做的:

ps -fe | awk '{ if ( tolower($0) ~ /network/ || NR == 1 ) print $0}'
    

1
投票
我写了一个脚本

hgrep

来替换命令
grep

#!/bin/bash content=`cat` echo "$content" | head -1 echo "$content" | tail -n+2 | grep "$@"
然后

df -h | hgrep tmpfs

将输出标题和行包括
tmpfs

报价至关重要。


0
投票
嗨,好奇你可以在 cmd 中使用 xargs。

find /mahesh -type f |xargs -I {} -t /bin/sh -c "head -1 {}>>/tmp/out.x|grep -i 6330162 {} >>/tmp/out.x"

其中 /mahesh 是文件所在的目录,输出放置在 /tmp/out.x 中


0
投票
如果perl可以的话,你可以使用:

some-command | perl -ne 'print if $.==1 | /some-stuff/'


    


0
投票
一个简单但不是 100% 准确的方法是添加行号并在搜索模式中包含

^1:

。
无标题:

netstat -lt | grep "LISTEN"

带有标题和行号:

netstat -lt | grep -n ^ | grep "^1:\|LISTEN"

注意:grep "AAA|BBB" --> 与 AAA 或 BBB 匹配行。

© www.soinside.com 2019 - 2024. All rights reserved.