Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed not writing to file

Tags:

bash

sed

I am having trouble using sed to substitute values and write to a new file. It writes to a new file, but fails to change any values. Here is my code:

cd/mydirectory  

echo "Enter file name:"
read file_input

file1= "$file_input"
file1= "$file1.b"

file2= "$file_input"
file2= "${file2}Ins.b"

sed "/\!cats!/s/\!cats!.*/cats!300!/g $file1>$file2

I simply want to substitute whatever text was after cats with the value 300. Whenever I run this script it doesn't overwrite the previous value with 300. Any suggestions?

like image 888
OldMopMan Avatar asked Oct 21 '22 06:10

OldMopMan


1 Answers

Try changing

sed "/\!cats!/s/\!cats!.*/cats!300!/g $file1>$file2

to

sed "s/cats.*/cats300/g" $file1 > $file2

To replace text, you often have to use sed like sed "s/foo/bar/g" file_in > file_out, to change all occurrences of foo with bar in file_in, redirecting the output to file_out.


Edit

I noticed that you are redirecting the output to the same file - you can't do that. You have 2 options:

  • Redirect the results to another file, with a different filename. e.g.:

    sed "s/cats.*/cats300/g" $file1 > $file2.tmp
    

    Note the .tmp after $file2

  • Use the -i flag (if using GNU sed):

    sed -i "s/cats.*/cats300/g" $file1
    

    The i stands for inline replacement.

like image 152
jimm-cl Avatar answered Nov 03 '22 20:11

jimm-cl