Reading some lines from a file in terminal
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 ;)