TheVirtuoso
TheVirtuoso

Reputation: 65

Running a bash script that contains sed commands produces no results and just hangs. Why?

I have the sample code and the desired output below

Sample:

void function_patternWD1()
{
   some_code;
   some_code_patternWD3;
   some_code;
}
/*some_comments_patternWD2*/

void function_patternWD4()
{
   some_code;
   some_code_patternWD6;
   some_code;
}
/*some_comments_patternWD5*/

Desired Output:

void function_patternWD1()
{
   some_code;
   new_line_of_code_1;     //after sed command
   some_code_patternWD3;
   some_code;
}
/*some_comments_patternWD2*/

void function_patternWD4()
{
   some_code;
   new_line_of_code_2;    //after sed command
   some_code_patternWD6;
   some_code;
}
/*some_comments_patternWD5*/

What I've tried:

#!/bin/bash

if [ "$1" = "fileName" ]; then
   sed -e'/patternWD1/,/patternWD2/{/patternWD3/i new_line_of_code_1;' -e '}'
       -e'/patternWD4/,/patternWD5/{/patternWD6/i new_line_of_code_2;' -e '}' < "$1"
fi

Initially, I had tried

#!/bin/bash

if [ "$1" = "fileName" ]; then
   sed -e'/patternWD1/,/patternWD2/{/patternWD3/i new_line_of_code_1;}' < "$1"
fi

But it wasn't working so I asked a question here and a contributor corrected it for me to

#!/bin/bash

if [ "$1" = "fileName" ]; then
   sed -e'/patternWD1/,/patternWD2/{/patternWD3/i new_line_of_code_1;' -e '}' < "$1"
fi

which works fine with the single command but when I use it like in What I've Tried:, the script doesn't seem to work as it hangs and I don't see any results.

Can someone please explain the syntax behind this particular command usage, and why my command didn't work but the other one did?

Upvotes: 2

Views: 88

Answers (1)

Gorgor
Gorgor

Reputation: 62

As people already commented, you are missing a backslash to tell bash that your command spans two lines.

If you put the closing brace directly after the semicolon, sed will interpret it as belonging to the string you want to insert. Therefore, you have to end the string by closing the expression and putting the closing brace into its own expression.

If you need to match the indentation of the surrounding code, you need to escape the first space to make sed realize that the string you want to insert is starting. In your case, where there are three spaces for indentation, put backslash and three spaces before new_line_of_code.

With these changes applied, the relevant lines are:

sed -e'/patternWD1/,/patternWD2/{/patternWD3/i \   new_line_of_code_1;' -e '}' \
    -e'/patternWD4/,/patternWD5/{/patternWD6/i \   new_line_of_code_2;' -e '}' <"$1"

Upvotes: 2

Related Questions