【发布时间】:2014-04-08 05:11:03
【问题描述】:
您好,我必须编写一个简短的程序来接收输入并将其添加到文件顶部,并将时间戳添加到文件底部,也在 html 注释中。只是有点困惑如何做到这一点
echo "What would you like to add to the top of the file
read x
cat $x >> File1
但这是在文件末尾添加这个?提前致谢!
【问题讨论】:
您好,我必须编写一个简短的程序来接收输入并将其添加到文件顶部,并将时间戳添加到文件底部,也在 html 注释中。只是有点困惑如何做到这一点
echo "What would you like to add to the top of the file
read x
cat $x >> File1
但这是在文件末尾添加这个?提前致谢!
【问题讨论】:
echo "What would you like to add to the top of the file
read x
sed -i '1s/^/$x/' file
【讨论】:
这就是 shell 的分组结构派上用场的地方:
comment () { echo "<!-- $* -->"; }
read -p "what?" top
{ comment "$top"; cat $htmlfile; comment $(date); } > $htmlfile.new
【讨论】:
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"
【讨论】:
#!/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"
【讨论】:
mktemp 避免不雅。