0

I have a file which is 2760 lines with an id on line 2740. In the results I always need it to output line 7 from the top. There are files which contain many more lines and some which contain less but the output is always the value on line 7.

I'm using grep 'PATTERN' | sed -n '7p' yyyymmdd*.log this seems to match the pattern but output line 7 from the first file found in the directory.

Would appreciate if someone could give me a push in the right direction?

  • 1
    did you mean to write grep 'PATTERN' yyyymmdd*.log | sed -n '7p' ? also, add sample input(s) and expected output for clarity – Sundeep Sep 6 '16 at 13:23
  • already tried that but it doesn't return anything. – Samosa Sep 6 '16 at 14:45
  • did you try the answer by @Archemar? and as I asked before, give us sample input files (say 10 lines each) and expected output... – Sundeep Sep 6 '16 at 15:01
  • 1
    I don't understand the question. Do you want the 7th line from each file? The 7th line containing PATTERN from each file? The 7th matching line from the concatenation of the files? Something else? Please edit to clarify. – Gilles Sep 6 '16 at 22:03
0

I would try

awk '/PATTERN/ { c[FILENAME]++ ; if (c[FILENAME]==7) print ; } ' yyyymmdd*.log

where

  • the c[FILENAME] trick will select 7th line on each file.
0

With GNU sed, that should be possible. For example, in order to only display line number if it includes the PATTERN from your file yyyymmdd*.log, try:

sed -n '2740s/PATTERN/PATTERN/p' yyyymmdd*.log

That will preface the search command to sed with the specified line number (2740), and -n and p will suppress output unless it's matched.

0

You need line 7 of each input file matching a particular filename pattern?

awk 'FNR==7' file*

The awk variable FNR will be the line number of the current input file. If it is 7, the line is printed.

Or, with GNU sed:

sed -n -s '7p' file*

The GNU sed option -s will make the internal line counter reset between input files (this is a GNU extension to standard sed)

If you need to filter the result on some regular expression, either just pipe the output through grep 'PATTERN' or, with awk:

awk 'FNR==7 && /PATTERN/' file*

or, with GNU sed:

sed -n -s '7{/PATTERN/p}' file*

Your command:

grep 'PATTERN' | sed -n '7p' yyyymmdd*.log

Some issues:

  1. The grep has no input and will be waiting for input on its standard input stream.
  2. The sed will only pick up the 7th line from the complete set of input files (i.e. only from the first file). Its line counter does not reset between files. Using GNU sed with -s, as above, fixes this.
  3. The two parts of the pipeline are not connected. sed will not read from grep.
  4. The grep is not needed. You just need line 7.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.