0

I want to practice using head, uniq and cut, for this data here. I know this thread but it focuses too much on cat and external programs.

I would like a simpler answer.

I want to take interval from the data file, e.g. lines 800-1600. I am not sure if cut is intended for this task with the flags -n and -m. At least, I could not extract lines, just patterns in some byte locations.

Running mikeserv's answer

Code 1.sh:

for i in 2 5
do    head -n"$i" >&"$((i&2|1))"
done <test.tex     3>/dev/null

and data

1
2
3
4
5
6
7
8
9
10
11

Running the code as sh 1.sh gives empty line as an output, although it should give 3 4 5 6 8. What do I understand wrong in Mike's answer?

How would you select line intervals in data by sed, tail, head and cut?

2 Answers2

3

Costas' elegant answer in comment

sed '800,1600 ! d' file
terdon
  • 242,166
1
for i in 799 800
do    head -n"$i" >&"$((i&2|1))"
done <infile     3>/dev/null

The above code will send the first 799 lines of an lseek()able <infile to /dev/null, and the next 800 lines of same to stdout.

If you want to prune those 800 lines for sequential uniques, just append |uniq. In that case, you might also do:

sed -ne'800,$!d;1600q;N;/^\(.*\)\n\1$/!P;D' <infile

...but a prudent gambler would put their money on head;head|uniq in a race.

If you want to process those lines for totally sorted uniques, then you can still use the first for loop and append instead:

... 3>/dev/null  | grep -n ''      | 
sort -t: -uk2    | sort -t: -nk1,1 | 
cut  -d: -f2-

In the latter case it's probably worthwhile to export LC_ALL=C first.

mikeserv
  • 58,310
  • 2
    @Masi - lseek() is the standard C lib function which enables an application to move leftward the r/w fd offset. In other words, it allows applications to easily rewind file descriptors. All regular files are required by POSIX to be lseek()able, but pipes and such almost definitely always won't be. – mikeserv Jun 26 '15 at 21:21
  • I added the output of your bash -command on a fixed input in OSX 10.8.5: empty line in the body of my question. Do you understand why it gives an empty line? – Léo Léopold Hertz 준영 Sep 11 '15 at 11:57