shell scripting: "formatting" issue with text files
Hello!
I'm trying to replace a value in a file, and to do this, I'm reading in line-by-line. If the line doesn't match I copy it over to a temporary file, and if it does match, I make my change and copy that over to the temp file. This works great, but I'm losing white spaces in the line (tabs and indents only). So it's basically pushing everything along the left edge, which is horrid. How can I go about fixing this? I tried using "sed" to change the value, but it doesn't work well when you include variables. Here's the current code that I'm using just in case someone is interested. while read line do if echo $line | grep -q "^default.*" ; then echo "default=${myval}" >> /tmp/lilo-copy.conf else echo $line >> /tmp/lilo-copy.conf fi done < /etc/lilo.conf mv /tmp/lilo-copy.conf /etc/lilo.conf original sed command I used: sed -e "/^default/ s/^default=.*/default=$myval/" /etc/lilo.conf |
Hi,
You don't need the first part of the sed command: sed "s/^default=.*/default=$myval/" /etc/lilo.conf Should replace all instances of default=.*, at the beginning of the line with default= and the content of $myval. If you have sed 4.x (sed --version) you can use the -i flag to instantly edit the infile (man sed for details). Hope this helps. |
You probably loose that whitespace because of
Code:
echo $line Code:
echo "$line" But then, the sed command should work fine unless $myval contains "/". Note that you may use any other character for that purpose in sed, as in Code:
sed "s|^default=.*|default=$myval|" /etc/lilo.conf > /tmp/lilo-copy.conf |
Thanks for the help guys! I ended up using your sed command (so much prettier).
|
All times are GMT -5. The time now is 11:45 PM. |