-1

Using sed I know how to delete certain line numbers like

sed -i.bak -e '6d;8d;15d;' file

How can I achieve the reverse of it. I want to keep those lines and delete the rest. I want to do this in place, as I have huge files and I'd use this as part of a larger script. I'm still keeping a backup as I don't want to mess up my original dataset.

RAVI
  • 53
  • 1
  • 6
  • 3
    Possible duplicate of [Bash tool to get nth line from a file](https://stackoverflow.com/questions/6022384/bash-tool-to-get-nth-line-from-a-file) – Benjamin W. Nov 27 '18 at 06:24
  • 1
    Specifically, the second answer contains your exact use case. – Benjamin W. Nov 27 '18 at 06:24
  • I was looking for something that does it in place. But yeah that does match to a large extent. Thanks. – RAVI Nov 27 '18 at 08:14

3 Answers3

1

The solution of RavinderSingh13 is nice and uses sed with the -n flag to suppress the automatic printing of the pattern space. If you do not want to use that flag, you can use a label and a sed-goto statement:

sed '6b;8b;15b;d;' file

This essentially states:

  • 6b If I am on line 6, branch to the end
  • 8b If I am on line 8, branch to the end
  • 15b If I am on line 15, branch to the end
  • d If I did not branch yet, delete the pattern space and start the next cycle

In this case, in contrast to the usage of the -n flag, the pattern space is always printed at the end of the cycle.

If you want to use awk, you can do:

awk '(FNR==6) || (FNR==8) || (FNR==15)' file
kvantour
  • 25,269
  • 4
  • 47
  • 72
1

Also :

sed -e '6!{8!{15!d;};}'
William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • 2
    LOL _This answer was flagged as low-quality because of its length and content._. Looks OK to me. Maybe a bit of an explanation? – kvantour Nov 27 '18 at 16:26
0

How about stopping the print for sed and mention wherever you want to print the lines then.

sed -i.bak -n '6p;8p;15p;' Input_file

From man sed:

   -n, --quiet, --silent

          suppress automatic printing of pattern space

   p      Print the current pattern space.
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93