Operating System - HP-UX
1832858 Members
3264 Online
110048 Solutions
New Discussion

Re: add new string using sed

 
Sergejs Svitnevs
Honored Contributor

add new string using sed

Hi all.

I have a shell variable $x.

# echo $x
HELLO UNIX

I also have an ASCII file hello.txt.

#cat hello.txt
HELLO LINUX
HELLO WINDOWS

How can I add a value of the shell variable $x to the end of my file using sed?

"cat $x >> hello.txt" is not useful to me.

Your help with SED statement is appreciated.

Thanks,
Sergejs
6 REPLIES 6
A. Clay Stephenson
Acclaimed Contributor

Re: add new string using sed

This is pointless to do with sed -- although it can be done. You should realize that sed can never edit a file directly; it creates a new file. Often a temp file is created based upon the input file and then the temp file is mv'ed to the input file.

This will worl just fine and will do the job with the file in place:
echo "${x}" >> hello.txt
If it ain't broke, I can fix that.
Kent Ostby
Honored Contributor

Re: add new string using sed

Sergejs --

Perhaps you could tell us more about the application that you want to use this in or explain why you want to use sed to do this operation ?

Best regards,

Kent M. Ostby
"Well, actually, she is a rocket scientist" -- Steve Martin in "Roxanne"
Sridhar Bhaskarla
Honored Contributor

Re: add new string using sed

Hi Segejs,

You will need to use 'echo' instead of "cat" to print $x into hello.txt.

echo "$x" >> hello.txt

If you insist of sed, below is the way

sed 's/$/'"$x"'/' hello.txt > 1
mv 1 hello.txt

-Sri
You may be disappointed if you fail, but you are doomed if you don't try

Re: add new string using sed

Hi

It's better to do that with ex :

#ex -s FILE << EOF
> /^TOTO/
> s/TOTO/TOTO2/
> w
> EOF

TOTO=variable
TOTO2=new variable

Best regards
Karthik S S
Honored Contributor

Re: add new string using sed

Since you are insisting on using sed :-)),

#echo >> hello.txt

#sed /^$/s/^$/"$x"/g hello.txt
HELLO LINUX
HELLO WINDOWS
HELLO UNIX

However here I assume that there are no blank lines else where in this file than the end of file.

-Karthik S S
For a list of all the ways technology has failed to improve the quality of life, please press three. - Alice Kahn
Karthik S S
Honored Contributor

Re: add new string using sed

Another method,

create a file (sedfile in this example) with the following two lines,

$a\
Whatever string you want


sed -f sedfile hello.txt

cat hello.txt
HELLO LINUX
HELLO WINDOWS
Whatever string you want

However sed can not substitute the variables with in the input file.

-Karthik S S

For a list of all the ways technology has failed to improve the quality of life, please press three. - Alice Kahn