Search code examples
bashsedwc

Remove half the lines of files recursively using sed and wc


I wonder if there is a way to remove half the lines of a file using wc and sed.

I can do this:

sed -i '50,$d' myfile.txt

Which removes lines from 50 to the end of file. I can also do this:

wc -l myfile.txt

Which returns the number of lines in the file.

But what I really want to do is something like this:

wc -l myfile.txt | sed -i '{wc -l result}/2,$d' myfile.txt
  1. How can I tell sed to remove the lines starting from the wc -l result divided by 2?
  2. How can I do this recursively?

Solution

  • I guess you were close. Just use a command substitution with arithmetic expansion to get the value of the starting line:

    startline="$(( $(wc -l <myfile.txt) / 2 ))"
    sed -i "$startline"',$d' myfile.txt
    

    Or a oneliner:

    sed -i "$(( $(wc -l <myfile.txt) / 2 ))"',$d' myfile.txt