Kevin Moy Kevin Moy - 1 month ago 5
Bash Question

Final command in script (sed commands) not working

I have a script file here, called

editfile.script
:

#!/bin/bash

sed '{
1i \Game Commence\nAre You Ready???\
s/game/Game/g
s/points/Points/g
s/the\sthe/the/g
/^ *$/d
$a It's time
}' "$1"


To edit this file named
GameOverview




This game will begin in 3 minutes.
The objective is to score 10 points.
If you score 10 points, u move to the the next round

Good luck, may the the force b w u


Now when I run
.\editfile.script GameOverview
(from the C shell) command line, I receive this output:

Game Commence
Are You Ready???
This Game will begin in 3 minutes.
The objective is to score 10 Points.
If you score 10 points, u move to the next round
Good luck, may the force b w u


As you can see, every command has been carried out: except for the append command
$a It's time
. Why has this happened, and how to fix? And I believe it has something to do with the preceding "delete all blank lines" command
/^ *$/d
, for when I got rid of it the "It's time" was appended:

Game Commence
Are You Ready???
This Game will begin in 3 minutes.
The objective is to score 10 Points.
If you score 10 points, u move to the next round

Good luck, may the force b w u
It's time

Answer

The problem is the single quote in the string you're appending, It's time. It ends the opening single quote of your sed command.

You can get a single quote by ending the first quote, putting your single quote between double quotes, then start another single quoted string:

$a It'"'"'s time

To avoid the problem altogether, you can put your sed commands into a separate file instead of wrapping it in a shell script:

$ cat sedscr.sed
1i\
Game Commence\nAre You Ready???
s/game/Game/g
s/points/Points/g
s/the\sthe/the/g
/^ *$/d
$a\
It's time

I've also split up the i and a commands across two lines, which should be the most portable way of issuing these commands.

You can then call it like this:

$ sed -f sedscr.sed GameOverview
Game Commence
Are You Ready???
This Game will begin in 3 minutes.
The objective is to score 10 Points.
If you score 10 Points, u move to the next round
Good luck, may the force b w u
It's time

Like this, you don't have to treat single quotes special.

Comments