[英]sed command throwing error in bash script
I have a simple Bash shell Script to loop through each file in a directory and check is the copyright message is at the top of the file. 我有一个简单的Bash shell脚本,可以遍历目录中的每个文件,并检查版权信息是否位于文件顶部。 If it's not there is should add it. 如果没有,则应添加它。
The script is giving an error when I try to use a variable in the sed command. 当我尝试在sed命令中使用变量时,脚本给出了错误。 I have looked at other similar questions and tried double quotes "", I have tried using a different operator but still can't find the solution. 我已经看过其他类似的问题,并尝试了双引号“”,但我尝试使用其他运算符,但仍然找不到解决方案。 Can someone possibly point out what I am doing wrong? 有人可以指出我做错了什么吗?
Msg='/*------------------------------------------------------------------------------
*******************************************************************************
* Copyright message here
*******************************************************************************
*----------------------------------------------------------------------------*/'
for file in *
do
if grep -Fxq "$Msg" $file
then
echo Marvel Message already exist: $file
else
if test -f "$file"
then
echo "Adding Message to file: $file"
sed -i "1s/^/${Msg}\n/" $file
fi
fi
done
I would not use sed for this. 我不会为此使用sed。 I would use ed: 我会用ed:
ed "$file" <<END
1i
$Msg
.
wq
END
Or, using sponge
from the moreutils package 或者,使用moreutils软件包中的sponge
{ echo "$Msg"; cat "$file"; } | sponge "$file"
Simply you can do it with marge like this, here with echo "$Msg" > tmp.txt
you are creating a file with your $Msg
as header of the tmp file. 只需执行以下操作即可完成此操作,在此处通过echo "$Msg" > tmp.txt
您将使用$Msg
作为tmp文件的标题来创建文件。 And with cat $file >> tmp.txt
you are merging the file. 使用cat $file >> tmp.txt
您正在合并文件。
for file in *
do
if grep -Fxq "$Msg" "$file"
then
echo Marvel Message already exist: "$file"
else
if test -f "$file"
then
echo "Adding Message to file: $file"
#sed -i "1s/^/${Msg}\n/" $file
echo "$Msg" > tmp.txt
cat "$file" >> tmp.txt
mv tmp.txt "$file"
fi
fi
done
Hope this will help you. 希望这会帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.