简体   繁体   中英

Simple bash scripting with echo, sed, and variables

I'm having this problem: I want to use the sed command to replace a line in a file,

sudo sed -i 's/option=setting A/option=setting B/g' ~configfile

This line should be part of a .sh file, so I added "> myscript.sh" (which is represented by variables below). I also have several possible options variables that are listed in a list:

options.list

Which contains

A

B

C

So, I want to search and replace a variable, no matter what it was, to the new value within the list. That's why I used option=.*$ in the first part of sed. The second part of the sed should combine the chain "setting= " with all the options from options.list. All that have to be pushed in a .sh file.

So, to combine the whole stuff I tried this:

while IFS= read -r file
do
     echo "#!/bin/bash" >> "$_dest""$file".sh
     echo sed -i 's/option=.*$/option="setting ""$file"/g' ~configfile >> "$_dest""$file".sh        
done < "$options.list"

But there is a problem with echo and sed, probably related with backslashes or something... I tried hard but still with no solution. SOrry I know this is probably a silly question :)

First, have you any error message?

You could try something like :

sed -i 's/\(option=\).*$/\1"setting '$file'"/g' ~configfile

I don't understand why you use echo before your sed. If you want to print the output of sed in the standard output (stdout), you could use sed without -i option. Be ware, -i option directly make the replacement into the input file.

Otherwise, is ~configfile the real name of your file ? If you want to use ~ like your own directory ( /home/your_name ), use it like this :

~/configfile

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM