LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   shell scripting: "formatting" issue with text files (http://www.linuxquestions.org/questions/programming-9/shell-scripting-formatting-issue-with-text-files-474532/)

eur0dad 08-16-2006 06:08 PM

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

druuna 08-16-2006 06:36 PM

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.

spirit receiver 08-17-2006 04:51 AM

You probably loose that whitespace because of
Code:

echo $line
Replace it with
Code:

echo "$line"
in both instances, as echo will interpret $line as a collection of separate arguments instead of a single argument that contains space characters.
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

eur0dad 08-17-2006 11:50 AM

Thanks for the help guys! I ended up using your sed command (so much prettier).


All times are GMT -5. The time now is 04:12 PM.