AnswerBun.com

Executing sed throws the error "unexpected EOF while looking for matching"

Unix & Linux Asked by TwystO on November 7, 2020

Here’s the problem.
I’m trying as "root" user to execute a command as "myusername" user.

That’s why I’m using su - $USERNAME -c <command>
The <command> itself is something like sudo sed -i 's|SEARCH_REGEX|REPLACEMENT|' /etc/cloud/cloud.cfg

But each time I execute my script I got an error which seems to be due to the REPLACEMENT part.
I guess this is something around carriage return or spaces.

Here’s the code:

#!/bin/bash
$USERNAME="myusername"
$USERPWD="[email protected]"
PATTERN='s|preserve_hostname:sfalse|preserve_hostname: truenmanage_etc_hosts: false|'
su - $USERNAME -c 'sudo -S bash -c "sed -i '$PATTERN' /etc/cloud/cloud.cfg"' <<< $USERPWD

And here’s the error I get:

 truenmanage_etc_hosts:: -c: line 0: unexpected EOF while looking for matching `"'
 truenmanage_etc_hosts:: -c: line 1: syntax error: unexpected end of file

The ressources that helped me:
https://linuxize.com/post/how-to-use-sed-to-find-and-replace-string-in-files/
https://linuxhint.com/50_sed_command_examples/

What am I doing wrong ?

One Answer

Thanks to @Quasimodo I finally managed to solve this issue.

First I enhanced the PATTERN readability by splitting the REGEXP and REPLACEMENT into two distinct variables.
Then basically what I made is to change single-quotes to double-quotes and vice versa.

REGEXP="preserve_hostname:sfalse"
REPLACEMENT="preserve_hostname: truenmanage_etc_hosts: false"
PATTERN="s/$REGEXP/$REPLACEMENT/"
su - $USERNAME -c "sudo -S bash -c 'sed -n -i "$PATTERN" /etc/cloud/cloud.cfg'" <<< $USERPWD

Note that I escaped the double-quotes around $PATTERN in the sed command.
And that's it!

Answered by TwystO on November 7, 2020

Add your own answers!

Related Questions

Compare strings with different encodings

1  Asked on February 25, 2021 by dk999

         

How to SSH from host to guest using QEMU?

4  Asked on February 25, 2021 by jobin

     

Rsyslog to limit backlogs on database?

0  Asked on February 24, 2021

       

Impala query Result Storing into variable

1  Asked on February 23, 2021 by harkirat-singh

 

“pkgProblem” error, can’t install package

0  Asked on February 22, 2021 by human_garbage

       

How to find out on which core a thread is running on?

1  Asked on February 22, 2021 by michel-gokan

         

Convert rows to column with same column 1 value

1  Asked on February 21, 2021 by lini

     

setxkbmap switches between 2 out of 3 layouts

1  Asked on February 17, 2021 by archer

       

packet_write_wait Broken pipe even leaving top running?

6  Asked on February 17, 2021 by toan-nguyen

 

Ask a Question

Get help from others!

© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP