1

for eg. input :

// copyright

package com.base

import com.base
import com.base
...

i want to replace the pattern "// copyright\n\n^package.*" with another string

i'm trying to do using

sed -e 's/.,^package/$(anotherString)/g' $text 
1
  • How many empty lines between // copyright and package ... ? One or two ? Your example has one empty line in between but you're saying you want to replace // copyright\n\npackage.* which means two empty lines in between... Commented Apr 16, 2015 at 17:18

1 Answer 1

2

Using sed

Here is a sed solution:

$ sed '\|// copyright|,\|^package|{s/^package/Something\nElse/p;d}' file
Something
Else com.base

import com.base
import com.base
...

Did you want to remove all of the original package line? If so, just a minor change is needed:

$ sed '\|// copyright|,\|^package|{s/^package.*/Something\nElse/p;d}' file
Something
Else

import com.base
import com.base
...

Using awk

$ awk '/^\/\/ copyright/,/^package/{if (/^package/) print "Something\nElse"; next} 1' file
Something
Else

import com.base
import com.base
...
3
  • I get "\|// copyright|,\|^pack ...": extra characters at the end of d command error using the first sed command (bash on macOS) - any ideas what's wrong? Commented Apr 20, 2021 at 9:22
  • @adamsfamily MacOS uses BSD tools instead of GNU. That makes for a wide variety of minor yet annoying incompatibilities. I don't have access to BSD tools to test this on but, based on past experience, I suspect that an extra semicolon is needed: try sed '\|// copyright|,\|^package|{s/^package/Something\nElse/p;d;}' file
    – John1024
    Commented Apr 20, 2021 at 21:36
  • thank you, it works like a charm! However, I just realized it hasn't entirely solved my problem, I have created another question if you are interested in checking it out: unix.stackexchange.com/questions/647980/… - thanks! Commented May 4, 2021 at 6:17

You must log in to answer this question.

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