Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux head/tail with offset

Is there a way in Linux to ask for the Head or Tail but with an additional offset of records to ignore.

For example if the file example.lst contains the following:

row01 row02 row03 row04 row05 

And I use head -n3 example.lst I can get rows 1 - 3 but what if I want it to skip the first row and get rows 2 - 4?

I ask because some commands have a header which may not be desirable within the search results. For example du -h ~ --max-depth 1 | sort -rh will return the directory size of all folders within the home directory sorted in descending order but will append the current directory to the top of the result set (i.e. ~).

The Head and Tail man pages don't seem to have any offset parameter so maybe there is some kind of range command where the required lines can be specified: e.g. range 2-10 or something?

like image 806
hash-bang Avatar asked Aug 13 '14 23:08

hash-bang


People also ask

Can head and tail be used together in Linux?

Use the head and the tail Together We've learned that the head command can give us the first part of a file, while the tail command can output the last part of the input file.

How do you use head and tail command in Linux?

It is the complementary of Tail command. The head command, as the name implies, print the top N number of data of the given input. By default, it prints the first 10 lines of the specified files. If more than one file name is provided then data from each file is preceded by its file name.

How would you display more than 10 lines when you use head and tail?

Use of Head Command By default, the 'head' command reads the first 10 lines of the file. If you want to read more or less than 10 lines from the beginning of the file then you have to use the '-n' option with the 'head' command.

What is the opposite of tail in Linux?

head is a basic opposite of tail in relation to what part of the file operations are performed on. By default, head will read the first 10 lines of a file.


2 Answers

From man tail:

   -n, --lines=K         output the last K lines, instead of the last 10;          or use -n +K to output lines starting with the Kth 

You can therefore use ... | tail -n +2 | head -n 3 to get 3 lines starting from line 2.

Non-head/tail methods include sed -n "2,4p" and awk "NR >= 2 && NR <= 4".

like image 192
that other guy Avatar answered Sep 23 '22 02:09

that other guy


To get the rows between 2 and 4 (both inclusive), you can use:

head -n4 example.lst | tail -n+2 

or

head -n4 example.lst | tail -n3 
like image 20
Farahmand Avatar answered Sep 21 '22 02:09

Farahmand