1836528 Members
3780 Online
110101 Solutions
New Discussion

shell scripting

 
SOLVED
Go to solution
Donna Powell
Advisor

shell scripting

I am in the process of writing a shell script that creates directories and copies in some files for the application to work, that's the easy part, the part that I am having a problem with is on of the files needs to be modified after I copy in a default copy. I am trying to use sed to replace a regular expression

DefPath=/home/mcltech/NetS24V3/subnet4/files
QuePath=/home/mcltech/NetS24V3/subnet4/queues
LogPath=/home/mcltech/NetS24V3/subnet4/log
BinPath=/home/mcltech/NetS24V3/bin

I need to replace subnet4 with a new subnet number that will be set in a variable earlier in the script.

My problem is, with using sed the changes are made and sent to standard output and when I try to use the w at the end of the substitution string it overwrites the complete file. Can anyone tell me how to make this change without overwriting the entire file?
5 REPLIES 5
linuxfan
Honored Contributor
Solution

Re: shell scripting

Hi Donna,

One of the ways you can do is

DefPath=/home/mcltech/NetS24V3/subnet4/files

DefPath=$(echo $DefPath | sed 's/subnet4/'$variable_defined_earlier'/')

Now, subnet4 in DefPath will be updated by the new variable you assigned early on in the script

Does this help?

-Ramesh

They think they know but don't. At least I know I don't know - Socrates
A. Clay Stephenson
Acclaimed Contributor

Re: shell scripting

Sorry Donna, sed doesn't work like that. In fact, other than the case where all the lines in a textfile are exactly the same both before and after would such an operation is not possible even using c. The standard method for doing what you are trying to do is to write to a tempfile and then rename the tempfile. Something like this:

TDIR=${TMPDIR:-/var/tmp}
PID=${$}
T1=${TDIR}/X${PID}_1.tmp

for FILE in ${FILELIST}
do
sed -e myscript ${FILE} > ${T1}
STAT=$?
if [ ${STAT} -eq 0 ]
then
mv ${T1} ${FILE}
else
echo "Sed failed for file ${FILE}; status ${STAT}." >&2
fi
done

Regards, Clay
If it ain't broke, I can fix that.
linuxfan
Honored Contributor

Re: shell scripting

Hi Donna,

I misread your question, if you are modifying the file after you copy it through your script then you will have to use a tempfile and then move it like clay suggested.

Unfortunately that's how sed works and we can't do anything about it

-Regards
Ramesh
They think they know but don't. At least I know I don't know - Socrates
Donna Powell
Advisor

Re: shell scripting

thanks for the help, I was trying to prevent creating a temporary file, but if this is the only way, then so be it.
Curtis Larson_1
Valued Contributor

Re: shell scripting

you can use the ex command if you don't want to create a tmp file and rename it.

ex -s -c "s/from/to/g|wq" yourFile

ex - yourFile <<-EOFILE
s/from/to/g
wq
EOFILE

you could do a seach on ex to find other examples