0

How can I insert space after pattern matches

File has data

cellAN2D
input a1
output z
cellAIOI2D2
input a2
output z2
cellXOR2
input b1
output zn

Whenever pattern is found I want to add space after it. And output will be

cell AN2D
input a1
output z
cell AIOI2D2
input a2
output z
cell XOR2
input b1
output z

I tried

sed  's/^cell/cell /g' file

But it did not work.

Further I want to replace the cell word in above output to module word giving output

module AN2D
input a1
output z
module AIOI2D2
input a2
output z
module XOR2
input b1
output z

Can i combine both steps together to get final output.

8
  • 1
    Your sed command is fine and is working as expected. For the modification you want, you have to just modify to 's/^cell/module /g'. If you have a case where your command didn't work, update the question with that case, adding the specific output you get (not only "it did not work" because this phrase alone is not helpful)
    – thanasisp
    Oct 28 '20 at 8:01
  • I am not getting any output using above sed command Oct 28 '20 at 8:07
  • Right. Because you use -i which means sed to do any changes in-place, so there is no output into the console, you edit directly the file. man sed for details.
    – thanasisp
    Oct 28 '20 at 8:09
  • when I used the command sed 's/^cell /module /g' file then also I am getting back my original file, cell is not replaced by module word nor did there is space after cell. Oct 28 '20 at 8:14
  • @NEHACHOUDHARY. That is the expected behavior. Are you looking for both output to console and a changed file?
    – fpmurphy
    Oct 28 '20 at 8:31
1

Try the following:

$ sed 's/^cell/module /' file | tee outfile && mv outfile file
module AN2D
input
output
module AIOI2D2
input
output
module XOR2
input
output

$ cat file
module AN2D
input
output
module AIOI2D2
input
output
module XOR2
input
output
$
1
  • @steeldriver. True. Modified answer.
    – fpmurphy
    Oct 28 '20 at 13:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.