Using
- a UNIX-like system
- some implementation of sed, I’m using GNU sed
- a shell, I’m using GNU bash
- text files
Introduction & Motivation
As a command-line user on many Unix-like systems, I often run into a simple problem: how do I (simply) selectively grab one line out of a text file — especially when I know it’s line number?
It sounds stupidly simple, but it may not be stupidly obvious even if you’ve used UNIX and UNIX-like systems for a while. An obvious approach is to head a text file and pipe it into tail, like so:
$ # print line 2 in myfile.txt $ head -2 myfile.txt | tail -1 $ # format: head -N myfile.txt | tail -1 $ # where N is line number
This is not exactly efficient, especially if the line number (N) is quite large, as head will print all lines up to N into stdout for tail to grab the last one. However, this is a natural and very easy task for sed.
Setup
Find a file you like, or create a text file with 10 or more lines, listing the line number on each line. Here is my text file:
$ cat sedme.txt one two three four five six seven eight nine ten
Exercise 1: Print Just One Line
$ sed -ne 2p sedme.txt two
Exercise 2: Print Several Lines
$ sed -ne 2,4p sedme.txt two three four $ sed -ne 2,10p sedme.txt two three four five six seven eight nine ten $ sed -ne 2,11p sedme.txt two three four five six seven eight nine ten
Note that it’s okay we asked for line 11 even though it doesn’t exist. It just printed up to the end of the file.
Exercise 3: Print Lines Based on a Pattern
$ sed -ne /two/,/four/p sedme.txt two three four
I imagine that some systems may require you to wrap the sed expression in quotes, like so.
$ sed -ne "/two/,/four/p" sedme.txt or $ sed -ne '/two/,/four/p' sedme.txt
Tell Me More
See sed’s info or man page for documentation. We used the following options (descriptions from “info sed” of GNU sed 4.1.2):
`-n'
`--quiet'
`--silent'
By default, `sed' prints out the pattern space at the end
of each cycle through the script. These options disable
this automatic printing, and `sed' only produces output
when explicitly told to via the `p' command.
`-e SCRIPT'
`--expression=SCRIPT'
Add the commands in SCRIPT to the set of commands to
be run while processing the input.
…and the following command:
`p'
Print out the pattern space (to the standard output). This
command is usually only used in conjunction with the `-n'
command-line option.
We will also used addressing by regular expression for exercise 3:
/regexp/
Match lines matching the regular expression regexp.
Isn’t it amazing how much you can write about something so simple and elegant?
