Operating System - Linux
1753928 Members
8756 Online
108810 Solutions
New Discussion юеВ

Challenging Script question

 
SOLVED
Go to solution
Unix or Linux?
Frequent Advisor

Challenging Script question

I have a file named File1 with the following data:
Line1
Line2
Line3
Line4
Line5

Im trying to write a script that takes two arguments. The first being a line of text and the second the name of the file above. How do I insert the first argument(line of text) into the first line of the file named above.

For example:

./scriptTest Hello this is a test File1

Would append File1 as such:
Hello this is a test
Line1
Line2
Line3
Line4
Line5
37 REPLIES 37
Mel Burslan
Honored Contributor

Re: Challenging Script question

header=$1
filename=$2
(echo $header ;cat $filename) > /tmp/mytmpfile
mv /tmp/mytmpfile $filename


one of the ways how to do it..

HTH
________________________________
UNIX because I majored in cryptology...
Mel Burslan
Honored Contributor

Re: Challenging Script question

forgot to add, if your comment is multiple words containing spaces, make sure to enclose it in quotes.
________________________________
UNIX because I majored in cryptology...
Pete Randall
Outstanding Contributor

Re: Challenging Script question

You're going to have to put quotes around the "Hello this is a test", then your script will look like:

echo $1 > /tmp/file
cat $2 >> /tmp/file
cp /tmp/file $2


Pete


Pete
James R. Ferguson
Acclaimed Contributor

Re: Challenging Script question

Hi:

Using the shell only:

cat ./insertit
#!/usr/bin/sh
echo "${1}" >> "${2}.new"
cat ${2} >> "${2}.new"
mv "${2}.new" "${2}"

# ./insert it ok yourfile

Regards!

...JRF...
Unix or Linux?
Frequent Advisor

Re: Challenging Script question

Hi is there any other way to do it without having to use quotes. I cant say to the user if you have more than one word then put quotes around it.

So far I have managed the following.

sed -e '1i\' -e "$*" > File1

But this appends the whole line including the second argument.
Rodney Hills
Honored Contributor

Re: Challenging Script question

Can you have the users put the filename first, then-

f=$1
t=/tmp/hold$$
shift
echo $* | cat - $f >$t
mv $t $f

HTH

-- Rod Hills
There be dragons...
Sandman!
Honored Contributor

Re: Challenging Script question

How about the following:

echo hello this is a test file1 | awk '{
for(i=1;i $NF
}'

cheers!
Unix or Linux?
Frequent Advisor

Re: Challenging Script question

Hi

The line of text has to come first then the file name.

Thank you
Unix or Linux?
Frequent Advisor

Re: Challenging Script question

Hi Sandman


Im not sure that will work. How does the script know to echo the line of text: Hello this is a test, unless you manually type it in the script.

It could be any line of text.