-4

I want to write a script that displays the third line of a file, for example, filename.txt using only grep, without using backticks, &&, || or ; or sed and awk in only one line.

So I have tried this command: grep -w "3" filename.txt but it doesn't seem to work, any rectifications?

Compo
  • 36,585
  • 5
  • 27
  • 39
Crezcenz
  • 5
  • 2
  • 1
    You're not searching for a pattern .. That's what `grep` is for. I don't understand the reluctance to use `cat` or `head` ? – Zak Mar 13 '23 at 20:08

4 Answers4

2

You don't need grep since you aren't searching for a pattern, you want line #3 (or line N).

To get line 3 you can output the first 3 lines from the file, then take the last line from those three:
head -3 filename.txt | tail -1

You mention backticks, so if you want to assign that, or output it, enclose it in $(...) instead of backticks.
linethree=$(head -3 filename.txt | tail -1)

If the file is very large and the line N you want is far into the file it would be more efficient to use sed, such as
sed 4321q;d filename.txt or
sed <n>q;d filename.txt
as outlined in this answer.

Stephen P
  • 14,422
  • 2
  • 43
  • 67
  • This is the most appropriate answer .. Grep is not intended to be used in the way OP is asking. – Zak Mar 13 '23 at 20:07
  • It is more appropriate to do this with `sed` or `awk`, but the OP wants only `grep`. – M. Nejat Aydin Mar 13 '23 at 20:10
  • @M.NejatAydin - the OP wants line N and thought grep was the way to get it. As an [XYProblem](https://xyproblem.info/) X is "I want line #3" and Y is "how do I get line 3 from grep" having assumed the solution is grep. – Stephen P Mar 13 '23 at 20:13
  • There is no disagreement about `grep` being a wrong tool for this task. A single call to `sed` or `awk` would do the trick. – M. Nejat Aydin Mar 13 '23 at 20:22
1

Using BASH version 4 or higher mapfile:

Use mapfile to read third line only -s 2 discards 2 lines and -n 1 copies only 1 line into array named third_line:

mapfile -s 2 -n 1 third_line < filename.txt

Output array contents:

printf "%s" "${third_line[@]}"
j_b
  • 1,975
  • 3
  • 8
  • 14
0

You can use grep -n to number the lines, then you can pipe the output to another grep to extract the third line:

grep -n ^ file | grep ^3:

If you need to remove the 3: from the beginning of the line, you can pipe it to

| cut -f2- -d:

or, if you insist on grep, you can use

| grep -Po '(?<=^3:).*'

i.e. only output the part preceded by 3: at the beginning of a line (but -P is not supported everywhere).

choroba
  • 231,213
  • 25
  • 204
  • 289
0

If tail is allowed:

grep --after-context=2 -m 1 -e ".*$" filename.txt | tail -n1
Dan Stoner
  • 21
  • 2