Link to home
Start Free TrialLog in
Avatar of Mrdogkick
Mrdogkick

asked on

basic unix help....

I have started the code below and am stuck. What I want it to do is in the function, tell it to add the 'text' (which the user inputs) to the begining of a file I have already created called 'text' which  already contains numerous lines of text. Make any sense?


#!/bin/bash
 
function addText()
{
 
}
 
echo "Enter some text:"
read text

Open in new window

Avatar of omarfarid
omarfarid
Flag of United Arab Emirates image

#!/bin/bash
 
function addText()
{
 echo $text >  /tmp/f.$$
cat $file  >>  /tmp/f.$$
mv /tmp/f.$$  $file
}
 
echo "Enter some text:"
read text
addTex

Here file is a variable that contains file name
Avatar of Mrdogkick
Mrdogkick

ASKER

I put this in

$file=/home/hussain.ahmed/coursework/chapter7/text


but it says this

firstline: line 3: =/home/hussain.ahmed/coursework/chapter7/text: No such file or directory
Can you show the script and how you run it?
the code is below and I am running it by doing the following:

sh firstline
#!/bin/bash
 
$file=/home/hussain.ahmed/coursework/chapter7/text
 
function addText()
{
 echo $text >  /tmp/f.$$
cat $file  >>  /tmp/f.$$
mv /tmp/f.$$  $file
}
 
echo "Enter some text:"
read text
addText

Open in new window

Remove the $ from $file=/home/hussain.ahmed/coursework/chapter7/text

#!/bin/bash
 
file=/home/hussain.ahmed/coursework/chapter7/text
 
function addText()
{
 echo $text >  /tmp/f.$$
cat $file  >>  /tmp/f.$$
mv /tmp/f.$$  $file
}
 
echo "Enter some text:"
read text
addText
perfect, thanks a lot mate! One more thing. Is there a way I could append the text to the middle of the file??
Yes

length=`cat $file | wc -l`
mid=`expr $length / 2`
ed $file << END
$mid
a
$text
.
w
q
END
where would that fit into the script?
ASKER CERTIFIED SOLUTION
Avatar of omarfarid
omarfarid
Flag of United Arab Emirates image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
perfect, thank you very much!
could you please explain to me what you did in the solution. ie what does each line mean?
The code:

- calculate file length
- divide length by 2
- use ed editor to edit the file. The commands to ed are between << END and END.

You may refer to man ed to know how to use ed