OldMopMan
OldMopMan

Reputation: 57

sed not writing to file

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?

Upvotes: 5

Views: 7320

Answers (2)

jimm-cl
jimm-cl

Reputation: 5422

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.

Upvotes: 3

Qeole
Qeole

Reputation: 9174

I think this modified version of your script should work:

echo "Enter file name:"
read file_input

file1="$file_input"     # No space after '='
file1="$file1.b"        # No space after '='

file2="$file_input"     # No space after '='
file2="${file2}Ins.b"   # No space after '='

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

Note the single quotes around sed expression: with them, there's no need to escape the !s in your expression. Note also the double quotes around "$file1" and "$file2": if one of those variables contain spaces, this will prevent your command from breaking.

Some further remarks:

  • As pointed by jim, you may want to use the GNU sed -i option.
  • Your regex will currently replace everything after !cats! in matching lines. If they were several occurences of !cats! on your line, only one will remain. If instead you just want to replace the value between two ! delimiters, you may consider use following sed command instead:

    sed 's/!cats![^!]*/!cats!300/g'
    

Upvotes: 0

Related Questions