1

I want to be able to print the number of lines from bash as such: Line number (as counted from the top) -> end of the file

It seems tail will only count lines from the bottom.

Does anyone know how to do this? Thanks.

I've tried the following

# Where $1 is the file I'm reading in

# Get line number of error:
LINENUM=$( grep -n "$LAST_ERROR_DATE" $1 | egrep $LOG_THRESHOLD | grep $LAST_HOUR: | sed 's/:/ /g' | awk '{print $1}' | head -n 1 )

echo $LINENUM

# This returns 995

# Print everything from linenumber downwards
MESSAGE=$( awk 'NR >= $LINENUM' $1 )

This works when I manually pop in 995 to awk instead of $LINENUM, it doesn't seem to read in my bash variable. Any ideas?

bobinabottle
  • 569
  • 2
  • 7
  • 19

5 Answers5

9

Use tail -n +X filename to print from the Xth line to end of file.

womble
  • 95,029
  • 29
  • 173
  • 228
2

Single quotes '' mean, "use this exact string." They do not substitute variable names with their values. So that's why you have to manually write in 995. Does that help?

Wang
  • 226
  • 1
  • 5
  • Yep, that did the trick. Thanks! Changed to "NR >= $LINENUM" and it worked. – bobinabottle Nov 27 '09 at 18:59
  • Beware the side effects of using double quotes with awk in a shell script. `$1`, for example, means different things to the shell than to awk. Double quotes lets the shell expand it, single quotes do not. That's why you should use single quotes and variable passing as shown in my answer. – Dennis Williamson Nov 27 '09 at 19:34
1

Use sed -n 'N,$p' filename to print from the Nth line to the end of file.

nrgyz
  • 550
  • 2
  • 9
1

womble's answer is the best one, but to solve your problem with the variable in the last line, you can use awk's variable-passing feature:

MESSAGE=$( awk -v linenum=$LINENUM 'NR >= linenum' $1 )
Dennis Williamson
  • 60,515
  • 14
  • 113
  • 148
0

alternate:

line=10
file=/path/to/file
sed -n $line,\$p $file
Eddy
  • 842
  • 5
  • 8