Perform sed operations on given line numbers

You can use branches:

sed '
  1b1
  7b1
  14b1
  16b1

  # for the rest to be left alone, branch off (or delete them with "d"):
  b

  :1
  long_command'

(note that you can also add some 20,25b1 line ranges, or /re/b1 to include lines that match the re).

Or you could use awk:

awk 'NR == 1 || NR == 7 || ... {stuff}'

Or using a hash:

awk -v l=1,7,14,16 '
  BEGIN{split(l, a, ","); for (i in a) lines[a[i]]}

  NR in lines {stuff}'

(or BEGIN{lines[1]lines[7]lines[14]lines[16]} if there aren't too many)


Simply invert your selection and delete it:

sed '2,6d;8,13d;15d;17,$d;long_command'

Tags:

Sed