Quote:
Originally Posted by baks
HI, Im new to this forum and would like some help. I have created the following script which takes two arguments from the commandline and inputs the text from the first argument into the top line of the second argument(a file).
INPUT=$1
FIRSTLINEF=$2
TEMPFILE=TEMP
echo $INPUT > $TEMPFILE # User input will be placed in the temp file
cat $FIRSTLINEF >> $TEMPFILE # Contents of original file will be added
mv -f TEMP firstlinefile # Temp file will replace original file
I just have one question. How would I place the text entered at the commandline into the middle of a file. How would I manage it ?
|
What do you mean by "middle"? Do you mean the exact middle of the file, and, if so, do you mean by character or by line?
Quote:
I know I need to count the lines in the file and then use another temp file but Im completely lost.
I also cant use SED or AWK.
|
Why not? They are the logical tools to use.
To put something in the middle of the file, counting bytes rather than lines:
Code:
middle=$(( $( wc -c < FILENAME ) / 2 ))
{
dd bs=$middle count=1 2>/dev/null
printf "%s" "$INPUT"
cat
} < FILENAME > TEMPFILE
To put it in the middle by line:
Code:
middle=$(( $( wc -l < FILENAME ) / 2 ))
n=0
{
while [ $n -le $middle ]
do
IFS= read -r line
printf "%s\n" "$line"
n=$(( $n + 1 ))
done
printf "%s\n" "$INPUT"
cat
} < FILENAME > TEMPFILE