2

I have a file like this:

something

import (
    "foo1"
    "foo2"
    "foo3"

    "bar"

    "baz"
 )

something

something

I would like a shell command that as result will change the file to:

something

import (
    "foo1"
    "foo2"
    "foo3"
    "bar"
    "baz"
 )

something

something

Or with other words to remove the empty lines in the range of import ( to the closing ) and to leave the empty lines before and after.

1 Answer 1

3

sed is appropriate for this:

sed '/^import/,/^[[:space:]]*)/ { /^[[:space:]]*$/ d; }'

This command instructs sed to delete (d) every empty line (/^[[:space:]]*$/) located inside blocks of lines that start from "import" and end with a closing parenthesis (/^import/,/^[[:space:]]*)/)

3
  • I am trying this on mac and I get: sed: 1: "/^import/,/^[[:space:]] ...": extra characters at the end of d command
    – gsf
    Commented Jan 9, 2017 at 2:38
  • @gsf Can you test it with a semicolon between d and } please?
    – xhienne
    Commented Jan 9, 2017 at 2:44
  • Thanks a lot - this` '/^import/,/^[[:space:]]*)/ { /^[[:space:]]*$/ d; }' ` works
    – gsf
    Commented Jan 9, 2017 at 2:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .