1

I'm trying to edit a text file programmatically, which contains a line like this:

db.username="tata" db.password="toto" 

which I want to look like this:

db.username="fofo" db.password="bar" 

Here is the regex :

 ^\s*db.username="([^"]*) 

when i try to use this command

sed -i -E '^\s*db.username="([^"]*)' 'fofo' file.txt 

I'm getting the error:

sed: -e expression #1, char 1: unknown command: `^' 
1
  • 2
    Welcome to the site. Your usage of the sed command is incorrect. The syntax for replacements is sed 's/regex/replacement text/' file. Also, please indicate how the solution you look for is to decide which line to act upon. Do you want to replace every occurence of tata with fofo / toto with bar, or just set the value of db.username to fofo and that of db.password to bar? Your examples implies the latter, but please specify it explicitly in your question.
    – AdminBee
    CommentedFeb 26, 2021 at 11:41

1 Answer 1

4

you are mixing grep's regex and sed's substitution.

use either

sed -e '/db\.username/s/"[^"]*"/"foo"/' txt db.username="foo" db.password="toto" 

where

  • /db\.username/ tell sed to operate on line whith db.username (. is special caracter in sed)
  • s replace
  • "[^"]*" a quote, any number of non quote, a quote by
  • "foo"
  • /db.username/ would match db_username, dbXusername ....

or

sed -e 's/db\.username="[^"]*"/db.username="foo"/' txt db.username="foo" db.password="toto" 

on a further note, sed can capture pattern

sed -e 's/db\.username="\([^"]*\)"/usename is \1/' txt usename is tata db.password="toto" 
  • \( \) capture text
  • \1 use first captured text

grep can too

grep -Eo '"[^"]*"' txt "tata" "toto" 
0

    You must log in to answer this question.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.