LaPalme
LaPalme

Reputation: 339

sed : add something at the end of each line preceding a pattern

I would like to add a semicolon at the end of each line preceding a pattern. For example, I have the following text :

INSERT INTO line 1
INSERT INTO line 2
line 3
line 4
line 5
INSERT INTO line 6

And I would like to have this :

INSERT INTO line 1;
INSERT INTO line 2
line 3
line 4
line 5;
INSERT INTO line 6;

I first used the sed command :

sed -i '/^INSERT/ s/$/;/'

But the problem is that I will have a semicolon at the end of line 2 and not at the end of line 5. What would be the solution to do this automatically at the end of each line preceding an INSERT INTO in a file with thousands of samples like this one ?

Thank you for your time !

Upvotes: 0

Views: 172

Answers (1)

signjing
signjing

Reputation: 98

1 store the text into a file:
cat data.txt
result:

INSERT INTO line 1
INSERT INTO line 2
line 3
line 4
line 5
INSERT INTO line 6

2 the awk script content is:
cat awk.script
result:

{
if (NR==1) {lastline=$0;}
if (NR>1 && $1 == "INSERT") {print lastline";";lastline=$0;} 
if (NR>1 && $1 != "INSERT") {print lastline;lastline=$0;}
}
END{if(lastline ~ /INSERT/) print lastline";";else print lastline; }

3 Execute the awk command:
awk -f awk.script data.txt
result:

INSERT INTO line 1;
INSERT INTO line 2
line 3
line 4
line 5;
INSERT INTO line 6;

Upvotes: 1

Related Questions