Question

I have a file pointed to by a user defined environmental variable $file defined as:

file='filename.groovy'

When I do:

echo $file

It prints correctly without any problem as:

filename.groovy

and when I do:

cat $file

Its successfully printing the content of the file 'filename.groovy'

Everything is perfect till here

But, the problem is :

When I'm trying to redirect the output of sed command as:

sed 's/def version = ".*"/def version = "'$version'"/' $file > $file

and then

cat $file

Its printing nothing i.e., my original file got truncated.

Why is it so ?

Please suggest the reason and solution to redirect the output of sed command to the file 'filename.groovy' by using the variable $file

Thanx in advance . . .

Was it helpful?

Solution

You cannot read a file and in the meanwhile redirect your output to it.

What you can do is to use -i parameter in sed, that updates the file:

sed -i 's/def version = ".*"/def version = "'$version'"/' $file

You can see an example in https://stackoverflow.com/a/16901328/1983854 I posted yesterday.

OTHER TIPS

> truncates the file before the command is run, but you can use sed -i to replace in a file in-place.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top