HyoDong Kim
HyoDong Kim

Reputation: 1

Removing a specified number of lines from both head and tail of a stream

k=$1
m=$2
fileName=$3 
head -n -$k "$fileName" | tail -n +$m

I have the bash code. when I execute it, it only removes less than what it should remove. like ./strip.sh 4 5 hi.txt > bye.txt should remove first 4 lines and last 5 lines, but it only removes first 4 lines and last "4" lines. Also, when I execute ./strip.sh 1 1 hi.txt > bye.txt, it only removes last line, not first line....

Upvotes: 0

Views: 127

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295650

#!/bin/sh
tail -n +"$(( $1 + 1 ))" <"$3" | head -n -"$2"

Tested as follows:

set -- 4 5 /dev/stdin # assign $1, $2 and $3
printf '%s\n' {1..20} | tail -n +"$(( $1 + 1 ))" <"$3" | head -n -"$2"

...which correctly prints numbers between 5 and 15, trimming the first 4 from the front and 5 from the back. Similarly, with set -- 3 6 /dev/stdin, numbers between 4 and 14 inclusive are printed, which is likewise correct.

Upvotes: 2

Related Questions