2014-03-05 36 views
0

您好,我必须编写一个简短的程序来接收输入并将其添加到文件的顶部,并在html注释中添加时间戳到文件的底部。只是有点困惑如何做到这一点在bash顶部添加html注释

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

但是,这是在文件的末尾添加这个?提前致谢!

+0

可能重复http://stackoverflow.com/a/9533736/975114 – Amit

回答

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" 
+0

使用'mktemp'来避免激活。我知道当然是 –

+0

。值得注意的是,从我猜测的OQ来看,这不会成为问题,并且这种方式的例子更具可读性。 –

0
read -p 'What would you like to add at the top of the file?' header 
cat - "$oldfile" <<< "$header" > "$newfile" 

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" 
0

这里就是shell的分组构造派上用场:

comment() { echo "<!-- $* -->"; } 
read -p "what?" top 
{ comment "$top"; cat $htmlfile; comment $(date); } > $htmlfile.new 
0
echo "What would you like to add to the top of the file 
read x 
sed -i '1s/^/$x/' file