Bash: delete all input lines except the last n lines

I want to delete all lines except n last or first n lines with short single line

eg:.

---

aaaa

bbbb

cccc

dddd

cat/echo/find ...  | sed < all except last 2 lines > 

should succeed

aaaa

bbbb

---

aaaa

bbbb

cccc

dddd

eeee

ffff

cat/echo/find ...  | sed < all except last 2 lines > 

should succeed

aaaa

bbbb

cccc

dddd

---

I need this also for very high n's. That way, you could set n = 100 or so;)

Thanx for any help!

+4
source share
8 answers

To remove the last two lines, you can use something like this:

head -n $(($(wc -l < "$filename") - 2)) "$filename"

Not very elegant, but it should work. I use wc -l to count the number of lines, and then use the head to display only the first number of lines minus two lines.

EDIT: N ,

tail -n $N $filename

N , .

head -n $N $filename

, , , , .

+4

:

-n, --lines=[-]N
      print  the first N lines instead of the first 10; with the lead-
      ing ‘-’, print all but the last N lines of each file

, ... | head -n -2 , .

, , , .

tac file | awk 'NR>2' | tac
+4

, n

- ( n = 5):

tail -n5 $filename > $filename.tmp && mv $filename.tmp $filename

.

- , 5 , :

head -n$((`cat $filename | wc -l` - 5)) $filename > $filename.tmp && mv $filename.tmp $filename
0

3 :

set 3 inputfile; sed "$(($(sed -n $= $2)-$1+1)),\$d" $2
0

, 3, , :

$ cat -n file
     1  a
     2  b
     3  c
     4  d
     5  e
     6  f
     7  g
$ awk -v sz="$(wc -l < file)" 'NR>3' file      
d
e
f
g
$ awk -v sz="$(wc -l < file)" 'NR<=(sz-3)' file
a
b
c
d
0

1000 (: alert_PROD.log)

tail -1000 alert_PROD.log > alert_tmp ; cat alert_tmp > alert_PROD.log ; rm alert_tmp

1000 head tail:

head -1000 alert_PROD.log > alert_tmp ; cat alert_tmp > alert_PROD.log ; rm alert_tmp
0

:

, n :

head -n filename > new_filename

, n :

tail -n filename > new_filename

:

$cat test

1

2

3

4

5

6

7

-

$head -2 test

1

2

-1

awk -vn=2 -f rem.awk input.txt

rem.awk -

BEGIN { ("wc -l " ARGV[1]) | getline 
    a=$1-n+1 }     
NR<a { print }
-1

All Articles