Reading some lines from a file in terminal

22/07/2013

At work, I am often asked to find commands that meet specific needs. One of them recurs: how to make selections of lines in a file?

The question is very simple, some of you have got the answer. But when you’re not a “frequent terminal user” you can realize that it’s not as simple.

There are 4 commands to use:

  • head: get firsts lines of a file
  • tail: get last lines of a file
  • cat: get the whole content of a file
  • sed: to manipulate specific lines

“head” and “tail” commands have got an option to get a specific number of lines: “-n”

Let’s create a file to test:

my line 1 for foo
bar line 2
baz line 3
and another line 4
one more for 5
and the last 6

Save the content in “/tmp/example.txt”.

Ok now let’s test:

$ cat /tmp/example.txt
my line 1 for foo
bar line 2
baz line 3
and another line 4
one more for 5
and the last 6

$ head -n2 /tmp/example.txt
my line 1 for foo
bar line 2

$ tail -n3 /tmp/example.txt
and another line 4
one more for 5
and the last 6

Ok, but how to get line 4 of a file ? You can do it with head and tail… But the problem is that you will run 2 commands + an output redirection:

$ head -n 4 /tmp/example.txt | tail -n1
and another line 4

So, the “good” answer can be “use sed”, it will open file only one time:

$ sed -n "4p" /tmp/example.txt
and another line 4

How to read the command ?

  • sed -n => “-n” means “do not print anything”
  • “4p” => when line is number 4, “print” (command “p”)

“sed” can return a lineset, for example from line 3 to 5:

$ sed -n "3,5p" /tmp/example.txt
baz line 3
and another line 4
one more for 5

“head tail” (bad answer) equivalent, that runs 2 commands:

head -n 5 /tmp/example.txt | tail -n 2

You can get several lines, for example the line 2 and 4:

$ sed -n "2p; 4p" /tmp/example.txt
bar line 2
and another line 4

And for this example, there is no “head tail” equivalence that is easilly usable ;)

Ça peut vous intéresser aussi


Netcat, créez votre serveur en BASH

Bash est puissant, très puissant. Les commandes et utilisations sont vastes ...


Sauvegarde automatisé en Bash

On m’a demandé hier soir sur un canal IRC ...


Twitter client terminal

Je cherchais un outil pour twitter à utiliser depuis la ...


Traiter des listes correctement en Bash

Bien souvent j’utilise des fonctions de boucle en Bash ...

Merci de m'aider à financer mes services

Si vous avez apprécié cet article, je vous serai reconnaissant de m'aider à me payer une petite bière :)

Si vous voulez en savoir plus sur l'utilisation de flattr sur mon blog, lisez cette page: Ayez pitié de moi

Commentaires

Ajouter un commentaire

Ajouter un commentaire

(*) Votre e-mail ne sera ni revendu, ni rendu public, ni utilisé pour vous proposer des mails commerciaux. Il n'est utilisé que pour vous contacter en cas de souci avec le contenu du commentaire, ou pour vous prévenir d'un nouveau commentaire si vous avez coché la case prévue à cet effet.