【问题标题】:adding an html comment at the top in bash [duplicate]在bash的顶部添加一个html注释[重复]
【发布时间】: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

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

【问题讨论】:

标签: linux bash unix cat


【解决方案1】:
echo "What would you like to add to the top of the file
read x
sed -i '1s/^/$x/' file

【讨论】:

    【解决方案2】:

    这就是 shell 的分组结构派上用场的地方:

    comment () { echo "<!-- $* -->"; }
    read -p "what?" top
    { comment "$top"; cat $htmlfile; comment $(date); } > $htmlfile.new
    

    【讨论】:

      【解决方案3】:
      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"
      

      【讨论】:

        【解决方案4】:
        #!/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 避免不雅。
        • 我当然知道。关键是,从我猜的 OQ 来看,这不会有问题,而且这样的示例更具可读性。
        猜你喜欢
        • 2018-09-21
        • 1970-01-01
        • 2012-06-27
        • 1970-01-01
        • 2021-09-24
        • 1970-01-01
        • 2017-04-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多