[Unix] Cut Command To Extract A Particular Character based on Position

[How To] Cut Command To Extract A Particular Character based on Position

In today's post we will learn how to extract a particular character from a file when we know its exact position. Suppose we have a file output.sql as below


$ more output.sql
Connected to Oracle Database 11g Enterprise Edition Release 11.2.0.1.0
Connected as db_owner
53 rows inserted

In this scenario we wish to extract the number of rows inserted. We know for sure that the position of this info will always be in the first two characters of the last line.
Of course, there are simpler ways to do this using sed and awk, but the motive here is not simplicity but to understand the functioning of cut command.
We first extract the last line of the file using tail -1 command. We the pipe this output to the cut command to extract the exact number of characters. Using the cut command, we wish to extract 2 characters starting from first position, this can be achieved through cut -c1,2.

The final command to do this task will be:
$ more output.sql | tail -1 | cut -c1,2
53

Similarly some more scenarios are as follows:
1. Extract 4 characters starting from third position form all the lines in the file
$  more output.sql | cut -c3-7
nnect
nnect
 rows

2. Extract 1st and 4th character of each line from the file
$ more output.sql | cut -c1,4
Cn
Cn
5r

3. Extract first 4 characters of each line from the file
$ more output.sql | cut -c-4
Conn
Conn
53 r

4. Extract first word of each line from the file
$  more output.sql | tail -1 | cut -d' ' -f1-1 output.sql
Connected
Connected
53