Need help with sed command

Dear All,

I want to replace a value corresponding to particular variable in file using sed.
example

xValue 10.0;

I want to change its value to 19.1434 say.

xValue 19.1434;

How can I do that?

Thanks & Regards,
linuxUser_

Why use sed for this, a simple echo does everything you said you want:

echo 'xValue 19.1434;' > file
1 Like

Thanks a lot :slight_smile:

Dear Don Cragun,

echo making complete to replace with xValue 19.1434;
Infact I have to replace only one line :o

Thanks for help,

Regards,
linuxUser_

Try:

sed 's/xValue 10.0;/xValue 19.1434;/' file > newfile

If your version of sed supports the -i option:

sed -i 's/xValue 10.0;/xValue 19.1434;/' file 

Dear Franklin,

I want to replace xValue not only form 10 to 19.1434.
My shell command should work irrespective of the previous value.
means may be 10 to 19.1434
-10 to 19.1434
14876.897896 to 19.1434
How can I do that?

Thanks & Regards,
linuxUser_

sed 's/xValue .*;/xValue 19.1434;/' file > file.$$ && mv file.$$ file
1 Like

So you want the line that contains xValue anything; to become xValue 19.1434; , no other constraints/conditions? Try

sed 's/xValue .*;$/xValue 19.1434;/' file > newfile
1 Like

Dear Don Cragun,

You are expert.
I would like to see your posts with little explanation like in this command lines you are doing something like editing the file and saving in some temp files then copying to the original file (correct me if my understanding is wrong).

Thanks & Regards,
linuxUser_

The command:

sed 's/xValue .*;/xValue 19.1434;/' file > file.$$ && mv file.$$ file

directs the output from sed to a temporary file whose name ends with a period followed by the process ID of the shell that is running this command. If the sed command succeeds (exit status 0), the mv command is executed to replace the original file with the temporary file.

If the sed utility detects an error, the original file will not be changed, but after seeing the diagnostic message(s) produced by sed , you may need to manually remove the temporary file.

1 Like