2

I have an assignment of editing a text file, called LOLOLOL.

HRFJGEKGJHEJGKJVNEJGKJEG BOB BO B

GARY gARY gARY gary

FOG GARY bob bob bob Gary gary

the the bird in the the bush!

LOL MATE!

I have a bash script file called lolz.script:

#!/bin/bash

sed '1i Hee hee hee\n Ho Ho Ho\n' $1
sed 's/bob/Bob/g' $1

running .\lolz.script LOLOLOL at the command line, I get multiple iterations of the LOLOLOL text- precisely, one iteration per sed command.

For example, the output shows the first and second sed commands (applied for each) here:

*Hee Hee Hee 
Ho Ho Ho*
HRFJGEKGJHEJGKJVNEJGKJEG BOB BO B

GARY gARY gARY gary

FOG GARY bob bob bob Gary gary

the the bird in the the bush!

LOL MATE!
HRFJGEKGJHEJGKJVNEJGKJEG BOB BO B

GARY gARY gARY gary

FOG GARY *Bob Bob Bob* Gary gary

the the bird in the the bush!

LOL MATE!
  • --- * show the changed part of the text file in the output.

Whereas what I want output:

*Hee Hee Hee 
Ho Ho Ho*
HRFJGEKGJHEJGKJVNEJGKJEG BOB BO B

GARY gARY gARY gary

FOG GARY Bob Bob Bob Gary gary

the the bird in the the bush!

LOL MATE!

As you can see, each sed command is applied independently in each iteration of printing the text file. I need all sed commands to be applied together.

Note how the desired header from the first sed command is applied in the first iteration, while in the second it is not (but the bob to Bob change is).

Why has this happened, and what can I do to make commands in a script cumulative to one text file? This didn't seem to happen with same-format awk script.

2

Simply: you are invoking sed twice.

If you run those commands in a terminal one after the other, you will end up with two sets of output. Your script is just doing the same thing in its own shell.

You can use {} to group commands and put each one on a new line or use ; so all the commands act on the file cumulatively, calling sed only once:

#!/bin/bash
sed '{
     1i Hee hee hee\n Ho Ho Ho\n
     s/bob/Bob/g
}' "$1"

output of ./script file

Hee hee hee
 Ho Ho Ho

HRFJGEKGJHEJGKJVNEJGKJEG BOB BO B

GARY gARY gARY gary

FOG GARY Bob Bob Bob Gary gary

the the bird in the the bush!

LOL MATE!

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.