Ubuntu – Remove everything before first occurence of specified word

sedtext processing

How can I remove everything before the first occurence of a specified word using sed?

What I have tried so far:

echo $(cat /etc/nginx/sites-enabled/default | sed 's/^*.server/server/') > /etc/nginx/sites-enabled/default

I need to cleanup all the trash before I find the first "server" word.

Mainly I'd need a sed regex…

I have a Nginx default file with proxying info that is getting some leading spaces while the script is copying it to a Docker container and therefore it cant be strated. I'd need to delete it with some command.

File:

       server
{
listen 80 default_server;
location / 
{
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Connection "";
proxy_http_version 1.1;
proxy_pass http://127.0.0.1:5000;
}
}

I am not sure what kind of characters are there, so I'd like to remove everything before 'server'.

Best Answer

You simply remove every whitespace character (tabs, spaces, whatever) between the line start and the word "server" (only if there is nothing else but whitespaces) using the following simple command:

sed -i 's/^\s*server/server/' FILENAME

The -i option modifies the file in-place, that means all changes are applied and saved immediately and you don't get any output. If you don't want to rewrite the file and see the modified new version instead, omit the -i option and the command will print it to the STDOUT (standard output stream).

I use the regex ^\s*server to match any number of any kind of whitespaces between the line start and the word "server" inclusive, and let it replace those matches with the word "server" itself.