0

I am using environment variables and want to simply find a line containing environment variable and replace it with the entire line that consists of special characters.

Details: file="dir1/file1"

In short, I am trying to find a line in a file that contains $file and as soon as it finds it, replace entire line with the below line:

('test/$file', [your.name, your.age, your.address]), 

(please note the comma in end)

Command that I tried:

sed -i '/'$file'.*/c ('"'test/$file'"'," [hello.name, hello.age, hello.address]),' file_name

sed: 1: "file": invalid command code f

Please note that I want to replace the entire line. The problem lies with the complex string that I am replacing which consists of brackets, commas, slashes. It is not getting replaced.

misteriuos
  • 35
  • 3
  • 1
    It's not clear if you want `$project_path` expanded on the search or replace or both. Please show sample input and expected output. – Ed Morton Mar 15 '23 at 23:57
  • Again, please [edit] your question to include sample input and expected output that shows that. – Ed Morton Mar 16 '23 at 10:30

2 Answers2

1

Don't try to use sed for that as it doesn't understand literal strings (see is-it-possible-to-escape-regex-metacharacters-reliably-with-sed), use awk instead:

awk -v old="$project_path" \
    -v new="app('projects/$project_path', [hello.dev, hello.stage, hello.prod])," \
    'index($0,old){$0=new} 1' file

The above assumes $project_path doesn't contain escapes, if it can see how-do-i-use-shell-variables-in-an-awk-script for alternatives to -v, and that you want $project_path expanded in both the search and replacement strings.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
0

You could use:

sed -r "s:^.*[\$]file.*\$:('test/\$file', [your.name, your.age, your.address]),:g" file_name

Here:

  • : - delimiter of sed
  • ^.*[\$]file.*\$ - regex searching for your line
    • ^.* - everything from the beginning of line
    • [\$] - dollar sign in ERE regex
    • file - name of your "variable"
    • .*\$ - everything until the end of line

Also, notice all $ escaped with \, because replacement command enclosed in double quotes. I think escaping $ more pleasant for eye, than escaping single quotes.

misteriuos
  • 35
  • 3
markalex
  • 8,623
  • 2
  • 7
  • 32