使用涉及 echo 的 shell 脚本将学生 header 添加到 C++ 文件:将 \n 替换为实际的换行符,有什么方法可以改变行为?

Using a shell script involving echo to add student header to C++ files: Replaces \n with actual newline, any way to change behavior?

我正在上一门 C++ 课程,要求在每个提交的文件的顶部都有一个学生 header。输入它或 yank/paste-ing 是 所以 乏味,我一直在编写一个脚本来为我添加它。到目前为止,我有一些对我有用的东西,但我只是注意到它所操作的文件中任何字符串中的每个 \n 都被替换为实际的换行符。我猜这是在脚本中使用 catecho 的结果,我正试图弄清楚如何避免这种情况。

echo 的联机帮助页说默认行为是忽略反斜杠转义,但我不完全确定这与我正在尝试做的事情有何关系。

我的脚本是:

#!/bin/bash

NAME="Joseph Morgan"
CLASS="CISP 400 MoWe 3:00pm"
ASSIGNMENT=
DATE=$(date -I)

if [[ $# -eq 0 ]] ; then
    echo 'Argument required:'
    echo 'Usage: SOME_PROJECT_NAME [Adds project name to header] | d [Deletes header]'
    exit 0
fi

if [  == "d" ] ; then
    echo 'Deleting header - Be careful! If no header is present, the first five lines of your files will be deleted'
    read -p "Are you sure? (y/n)" -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]
    then
        for f in ./*.cpp ;
        do
            echo "$(tail -n +6 $f)" > $f
        done
        for f in ./*.h ;
        do
            echo "$(tail -n +6 $f)" > $f
        done
    fi
    exit 0
fi

for f in ./*.cpp ;
do
    echo -e "// $NAME\n// $CLASS\n// $ASSIGNMENT\n// $DATE\n\n$(cat $f)" > $f
done

for f in ./*.h ; 
do
    echo -e "// $NAME\n// $CLASS\n// $ASSIGNMENT\n// $DATE\n\n$(cat $f)" > $f
done

如果有其他方法可以完全做到这一点,请随时提出建议。我对在这里学习更感兴趣,该脚本仅供 fun/education 使用,因此它并不是非常重要。

谢谢!

问题出在给 echo(1) 命令的 -e 参数,这使得它将 \n 解释为一个新行。删除 -e 即可。我的意思是,当您编写自己的 headers 时,您 需要 -e,但您应该将 $(cat $f) 移到 "echo -e" 之外。例如,在两行中:

echo -e "// $NAME\n// $CLASS\n// $ASSIGNMENT\n// $DATE\n\n" > $f
echo "$(cat $f)" >> $f    # notice the double angle >>

但请注意,这会在读取文件之前将其擦除。即使在这里也有问题:

echo "$(tail -n +6 $f)" > $f

因为它可以在读取“$f”文件之前将其擦除(清空)。你可以这样做:

newcontent=$(tail -n +6 $f)
echo "$newcontent" > $f

因此,要添加您的 headers,请使用两个不同的回声,但在写入文件之前先阅读文件:

newcontent="$(cat $f)"
echo -e "// $NAME\n// $CLASS\n// $ASSIGNMENT\n// $DATE\n\n" > $f
echo "$newcontent" >> $f    # notice the double angle >>

希望对您有所帮助。