0

Hello i have to write a short program to take in an input and add it to the top of file and add a timestamp into the bottom of the file also in an html comment. just a little confused how to do this

echo "What would you like to add to the top of the file
read x
cat $x >> File1

But this is to add this at the end of the file? Thanks in advance!

user2569803
  • 547
  • 4
  • 10
  • 18

4 Answers4

0
#!/bin/bash

# No go, if file not existant
test -f "$1" || exit 1

# Need a temp filename. Yes, this is racy.
test -f "$1.tmp" && exit 1

# Read text
echo 'What would you like to add to the top of the file?'
read COMMENT

# Exit on empty text
test -z "$COMMENT" && exit 1

# Write header
mv "$1" "$1.tmp"
echo -n "<!-- $COMMENT -->" > "$1"

# Write content
cat "$1.tmp" >> "$1"
rm "$1.tmp"

# Write footer
TS=$(date)
echo -e "\n<!-- $TS -->" >> "$1"
Eugen Rieck
  • 60,102
  • 9
  • 66
  • 89
0
read -p 'What would you like to add at the top of the file?' header
cat - "$oldfile" <<< "$header" > "$newfile"

or

printf '%s\n' 'What would you like to add at the top of the file?' \
  '(hit ctrl-c on newline to commit, or ctrl-c to abort.)'
cat - "$oldfile" > "$newfile"
kojiro
  • 67,745
  • 16
  • 115
  • 177
0

Here's where the shell's grouping construct comes in handy:

comment () { echo "<!-- $* -->"; }
read -p "what?" top
{ comment "$top"; cat $htmlfile; comment $(date); } > $htmlfile.new
glenn jackman
  • 207,528
  • 33
  • 187
  • 305
0
echo "What would you like to add to the top of the file
read x
sed -i '1s/^/$x/' file
iamsrijon
  • 76
  • 6