Include header in the 'grep' result

2019-03-19 09:25发布

问题:

Is there a way to combine 'head -1' and 'grep' command into one for all the files in a directory and redirect the output to an output file. I can do this using 'sed' but it seems that it is not as fast as grep.

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

Using grep I can do the following one file at a time:

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

However, I need to do it for all files in the directory. Inserting a wildcard is not helping as it is printing headers first and then the grep output.

回答1:

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


回答2:

The following means you only need type the command once (rather than using && and typing it twice), it's also quite simple to understand.

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

e.g.

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

UPDATE: This only seems to work for ps, sorry, but I guess this is usually what people want this for.

If you want this to work for an arbitrary command, it seems you must write a mini script, e.g.:

#!/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

Which I've named hgrep.sh. Then you can use like this:

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

The nice thing about this approach is that we are using grep so all the flags work exactly the same.



回答3:

This will work by using a single receiving command:

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

It's also easy to use this with multi-line headers:

$ 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           

To reiterate, @samthebest's solution will only work in very specific situations; this will work with any command that writes to standard output.



回答4:

Hi Curious you can use xargs with your cmd.

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

Where /mahesh is dir in which your files are and output is placed inside /tmp/out.x



回答5:

I would have done that :

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


标签: shell grep