LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   insert string with sed (https://www.linuxquestions.org/questions/programming-9/insert-string-with-sed-257625/)

greg108 11-21-2004 12:58 PM

insert string with sed
 
I am writing a small bash script and I wanted to insert a string in front of every line of the file.
I tried to do something like that:

sed '/^/i\$STRING'

This doesn't work and I don't understand how to use an 'insert' option.

I need to insert my string from a variable and without a new line.

So let's say that:

STRING="beginning "

and line in the file is:

"and end"

then I want to make it:

"beginning and end"

I could also use different command. It doesn't have to be sed.
Thanks for any help.

david_ross 11-21-2004 01:26 PM

How about:
STRING="beginning"
sed s/^/$STRING/ somefile.txt

greg108 11-21-2004 01:47 PM

This one works. Thanks.
But it only affects output to the terminal.
To change the file I have to do something like that:

cat somefile.txt | sed s/^/$STRING/ > somefile.txt

Is there a nicer way to actually change the file?

david_ross 11-21-2004 01:54 PM

You can use -i:
sed -i s/^/$STRING/ somefile.txt

davidrr 11-21-2004 01:58 PM

If you do this:

cat somefile.txt | sed s/^/$STRING/ > somefile.txt

somefile.txt will be erased. Haven't you done the test ?
I suggest you the following:

sed s/^/$STRING/ somefile.txt > somefile.txt~ &&
mv -f somefile.txt~ somefile.txt

greg108 11-21-2004 02:09 PM

Quote:

Originally posted by davidrr
If you do this:

cat somefile.txt | sed s/^/$STRING/ > somefile.txt

somefile.txt will be erased. Haven't you done the test ?


Actually, it doesn't get erased. But thanks for the hint on alternative solution.


sed -i was what I needed.
Thanks

abhijeetudas 11-22-2004 01:11 AM

sed -i
 
hi

i was following this post
i noticed that if i use

cat file.txt | sed s/^/$STRING/ > file.txt

Well it works fine but not more than 8192 bytes ..
Just thought id let u know..
hey by the way thanks for the -i option
din know about it..


- Thanks..

buddy_epson 02-18-2005 01:11 PM

a thing of beauty
 
I'm a newbie to sed, but I've discovered how powerful it is, and simple to use once you get the syntax down. anway, I've been trying to find out (for awhile) how to do something as simple as inserting a character at the beginning of each line, and the manuals around are pretty much worthless. Just wanted to say thanks, because you've saved me a boatload of time and frustration on this one! (I wish I'd found it sooner)

Buddy


All times are GMT -5. The time now is 08:33 PM.