1

I've a simple text file, named samples.log. In this file I've several lines. Suppose I have a total of 10 lines. My purpose is to replace the first 5 lines of the file with the last file lines of the same file. For example:

line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9
line 10

Become:

line 6
line 7
line 8
line 9
line 10

In other words, I simply want to delete the first 5 lines of the file and then I want to shift up the last 5. I'm working on Linux. What is the most simple way to do this? Is there a command? I'm working on a C program, but I think that is better to execute the linux command inside the program, instead of doing this operation in C, that I think would be quite difficult.

LearningC
  • 88
  • 1
  • 8
  • What if the file has more than ten lines? Or fewer? Do you always want to just remove the first five, or always just keep the last five? – Biffen Sep 26 '22 at 11:07
  • (‘_better to execute the linux command inside the program, instead of doing this operation in C_’ a matter of opinion, perhaps, but starting a new process each time _might_ be bad for performance, and the risk of bugs _might_ be higher when constructing the command.) – Biffen Sep 26 '22 at 11:08

2 Answers2

1

Simply

  tail -n +6 samples.log

will do the job. tail -n +NUM file will print the file starting with line NUM

M. Nejat Aydin
  • 9,597
  • 1
  • 7
  • 17
0

You can use this command:

tail -n $(($(cat samples.log | wc -l) - 5)) samples.log

You calculate the total amount of lines:

cat samples.log | wc -l

From that, you subtract 5:

$((x - 5))

And you use that last number of lines:

tail -n x samples.log
Dominique
  • 16,450
  • 15
  • 56
  • 112
  • 1
    That's a [useless use of `cat`](https://stackoverflow.com/questions/11710552/useless-use-of-cat); the idiomatic solution is `wc -l – tripleee Sep 26 '22 at 14:57