Search code examples
sed

Issue with appending a line to a specific section of a configuration file using sed


I'm using MacBook M1 Ventura 13.3.1 (a)

Description: I am encountering a problem while trying to append a line to a specific section of a configuration file using the sed command in my bash script. Here are the details:

Problem Description: I have a configuration file named Kernel.php located in the app/Http directory relative to the root of my project. Within this file, there is an associative array with a key 'web' that represents a configuration section. I want to append a new line inside this section, just before the closing ], bracket.

Here's an example of what the section looks like before the modification:

'web' => [
    // ... other lines
],

I want to add a line like this inside the section:

    \App\Http\Middleware\HandleInertiaRequests::class,

Attempts Made: I've tried using various sed commands to accomplish this task, but none of them seem to work as expected. For instance, I've tried commands like:

sed -i '/^'\''web'\'' => \[/,/\],/ { /],/ i\
    \\\App\\Http\\Middleware\\HandleInertiaRequests::class,
}' app/Http/Kernel.php

Expected Outcome: I expect the sed command to find the section starting with 'web' => [ and ending with ],, then insert the new line \App\Http\Middleware\HandleInertiaRequests::class, just before the closing bracket ],. The resulting section should look like this:

'web' => [
    // ... other lines
    \App\Http\Middleware\HandleInertiaRequests::class,
],

Actual Outcome: However, the sed command is not working as expected, and it does not make the desired changes to the file.

I need assistance in finding the correct sed command or alternative approach to accomplish this task. Any help or suggestions would be greatly appreciated. Thank you!


Solution

  • This should work on Mac (BSD) sed:

    sed -i.bak -E "/'web' => \[/,/],/ { /(],)/s//    \\\App\\\Http\\\Middleware\\\HandleInertiaRequests::class,\n\1/; }" "app/Http/Kernel.php"
    
    'web' => [
        // ... other lines
        \App\Http\Middleware\HandleInertiaRequests::class,
    ],