In Bash, there are several ways to print a file while skipping a specified number of lines from the beginning. This can be particularly useful when dealing with large files and you’re only interested in a portion of the content.
Using tail
Command
The tail
command is primarily used to display the last part of a file, but it also has an option to start displaying from a specified line number. To skip the first X lines of a file, you can use the -n +X
option with tail
, where X+1
is the starting line number.
For example, if you want to print a file named huge-file.log
skipping the first 10 lines, you would use:
tail -n +11 huge-file.log
This command tells tail
to start printing from the 11th line of huge-file.log
, effectively skipping the first 10 lines.
Using sed
Command
Another way to achieve this is by using the sed
command, which is a powerful text editor that can also be used for filtering. To delete (or skip) the first X lines from a file, you can use:
sed '1,Xd' file.txt
Here, 1,Xd
means to delete (d
) lines from 1 to X.
Using awk
Command
The awk
command is a programming language designed for text processing. It’s also capable of skipping initial lines in a file. For instance, to print all lines after the first 1 million lines, you can use:
awk 'NR > 1000000' huge-file.log
Here, NR > 1000000
means that awk
should only consider (and thus print) lines whose line number (NR
) is greater than 1 million.
Choosing the Right Approach
- For simple line skipping: The
tail
command with its-n +X
option is straightforward and efficient. - For more complex text processing: If you’re also doing other manipulations,
sed
orawk
might be a better choice due to their powerful filtering capabilities.
Example Usage
Suppose you have a large file named example.log
, and you want to print everything except the first 100 lines. Here’s how you can do it:
# Using tail
tail -n +101 example.log
# Using sed
sed '1,100d' example.log
# Using awk (assuming integer numbers)
awk 'NR > 100' example.log
Each of these commands will display the contents of example.log
, starting from line 101.
In conclusion, skipping initial lines in a file can be easily achieved with Bash using tools like tail
, sed
, or awk
. The choice of tool depends on your specific needs and preferences.