views:

124

answers:

6

I want to put TextA to the beginning of TextB by

cat TextA A TextB

The problem is that I do not know how to refer to the first and second parameters, that is TextA and TextB in the following script called A:

  #!/bin/bash

  cat TextA > m1
  cat TextB > m2
  cat m1 m2 > TextB

where m1 and m2 are temporary files.

How can you refer to the two files in the shell script?

+2  A: 

you could just use append (>>)

cat TextB >> TextA

result is that TextA precedes text TextB in TextA

takete.dk
This is a problematic solution. This changes the file TextA, which I do not want to. For example, TextB is my essay, while TextA is a copyright notice. I want to use the same copyright notice for all my essays.
Masi
Then you can use: cat TEXTA TEXTB > TEXTA_BNote that you can't do cat TEXTA TEXTB > TEXTB because the shell opens TEXTB for writing before cat opens it for reading. This will cause TEXTB to be cleared before it's used, and the effect will be the same as: cat TEXTA > TEXTB
Nathan Fellman
+4  A: 

You can use $0, $1, $2 etc. to refer to the variables in the script.

$0 is the name of the script itself
$1 is the first parameter
$2 is the second parameter
and so on

For instance, if you have this command:

a A1 A2

Then inside a you'll have:

$0 = a
$1 = A1
$2 = A2
Nathan Fellman
Thank you for your answer!
Masi
I accept the answer, since it is an answer to my original question. Please, see my answer at the bottom. The command tee finally solved me the problem.
Masi
What I would do in this case, if I wanted to share the solution, is post a new question "how can I prepend file a to file b without using a temporary file?" and then post the answer to that.
Nathan Fellman
+3  A: 

In a bash script is the first parameter is $1, the second is $2 and so on.

If you want a default value for example the third parameter you can use:

var=${3:-"default"}
seb
I didn't know about the defaults. Thanks!
Nathan Fellman
A: 

Looks like you can just do the following:


TextA="text a"
TextB="text b"
echo "$TextA $TextB" > file1

Or use the append (>>) operator.

Nikolai N Fetissov
+1  A: 

I would do the following:

#!/bin/bash

if [ $# -ne 2 ]
then
  echo "Prepend file with copyright notice"
  echo "Usage: `basename $0` <copyright-file> <mainfile>"
  exit 1
fi

copyright=$1
mainfile=$2

cat $mainfile > /tmp/m.$$
cat $copyright /tmp/m.$$ > $mainfile

#cleanup temporary files
rm /tmp/m.$$ /tmp/m2.$$
Alex B
+1  A: 

I am surprised that nobody suggests the following result

cat TextA TextB | tee > TextB

This way, you can avoid the hassle of creating a temporary file.

Masi
does this work when TextB is too large to fit in memory? In that case tee might start overwriting TextB before cat finishes reading it all.
Nathan Fellman
@Nathan: Good point! I am not sure. I have not yet have an issue with memory. Do you know which is the memory limit?
Masi