I was told awk is great for working with columns of data. From what I have seen it's pretty cool, but I haven't found a good site that shows useful (to me) commands. What I'm looking for are the commands that print out lines 5-10 or lines 30-70. The closest I've found was

# Print the last line
      {line = $0}
  END {print line}

and that's not what I need. What I am also looking for is a command that would write lines 1-10 to a file, that would make analysis so much more palatable. if anyone here has any suggestions that would be wonderful, thank you so much.


-Al

Dani AI

Generated

Quick, practical ways to do the line-range tasks you asked about — building on ’s tip that awk exposes record-number variables.

awk examples

# print lines 5..10 (inclusive)
awk 'NR==5,NR==10 { print }' filename

# write the first 10 lines to a file (shell redirection)
awk 'NR==1,NR==10 { print }' filename > first10.txt

# variable-driven range with early exit (good on huge files)
awk -v s=30 -v e=70 'NR>=s { print } NR==e { exit }' filename > 30-70.txt

These use awk’s range-pattern and NR-based tests; the GNU Awk manual documents NR/FNR, range patterns, and the usual redirection/exit behavior. GNU Awk manual. (gnu.org)

sed / head+tail alternatives

# sed prints lines 5–10
sed -n '5,10p' filename > out.txt

# head/tail: get lines 30–70
head -n 70 filename | tail -n 41 > out.txt
# or
tail -n +30 filename | head -n 41 > out.txt

sed’s address ranges are concise and very portable; head/tail combos can be faster for simple “grab a middle chunk” jobs. See the GNU sed manual and coreutils docs for details. GNU sed manual. (gnu.org)

Notes and gotchas

  • If you’re reading multiple files and want the first N lines of each file, use FNR (file-local record number) instead of NR: awk 'FNR<=10 {print}' file1 file2. (gnu.org)
  • For simple extraction to a single file, shell redirection (>) is easiest. If you redirect to many different files from inside awk, remember to close() those outputs to avoid hitting descriptor limits — awk keeps opened outputs until closed. (gnu.org)

If you want a tiny script tuned to your actual input (CSV, fields, headers), include a sample input and the exact lines you need; the patterns above cover most quick tasks.

Recommended Answers

All 2 Replies

I know this thread has gotten some view but no replies....does someone suggest I post this elsewhere so I can possibly get some help?

The awk internal variable NR tells you what line you are currently working on

awk 'NR > 4 && NR < 11' filename

O'Reilly book 'sed & awk' - the one with the the tarsiers on the front cover.
If you're going to use awk get that book.

If you're on Linux go to the gawk (GNU awk) user's guide -

http://www.delorie.com/gnu/docs/gawk/gawk_7.html

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.