1

I want to chop the top 13 and the last 6 lines from a file

There are several answers on unix/linux but they aren't working for me as the sed options used aren't available on osx, tac isn't available, etc.
Si I am posting here for a q&a that is specific to osx

Right now I am using

$ cat myfile | tail -n+14 | sed '$d' | sed '$d' | sed '$d' | sed '$d' | sed '$d' | sed '$d'

but am looking for a shorter '1 step at the end' way.

1

Try this way:

sed '1,13d' filename | head -n -6

The sed command can be used to delete a range of lines. Here 1 and 13 are min and max line numbers.

1

Just for the fun of it:

sed -e '1,13d' -e $(($(wc -l <FILE)-6+1)),\$d FILE

Still needs two full passes over the input file though.

1

You can do it all with tail

tail -n+14 FILE | tail -r | tail -n+7 | tail -r
  • The first tail removes the top 13 lines
  • The second tail reverses the line order
  • The third tail removes the top 6 lines of the reversed order
  • The last tail reverses the line order again

or with awk (with inspiration from patrix)

awk -v n="$(wc -l FILE)" 'NR > 13 && NR < (n-6+1)' FILE
0

Here's my try, not so elegant but works:

cat myFile | tail -n+14 | head -n $[ $(wc -l myFile | awk '{ print $1 }') - 19 ]

Note: last 19 is 13 + 6

It's better to embed this into a script:

#!/bin/bash                                                                                                                                                                                                        

FILE="$1"
HEAD_STRIP="$2"
TAIL_STRIP="$3"

cat $FILE | tail -n+$[$HEAD_STRIP + 1] | head -n $[ $(wc -l $FILE | awk '{ print $1 }') - $[HEAD_STRIP + TAIL_STRIP] ]
0

This will work with OSX's version of tail:

cat file.txt | tail -n +7 | tail -r | tail -n +14 | tail -r    

If you have gnu version of head (installed by: brew install coreutils) you can do:

cat file.txt | tail -n +7 | head -n -13
  • Besides the uuoc in both commands, you have the requirements backwards. – fd0 Sep 29 '15 at 13:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .