shell脚本问题 从指定文件倒数第4行添加内容

2025-03-25 00:38:21
推荐回答(2个)
回答1:

方法比较笨,但易理解,
#####将以下内容写成shell脚本即可#######

#按照"倒数第几行"的标准写的过程

if $# -ne 3
then
echo $0 "desfile setline srcfile "
echo "desfile= 需要修改的指定文档"
echo "setline= 从倒数第几行开始替换"
echo "srcfile= 提供待插入内容的文档"
echo "如果两个文档的目录不相同,入参时需要指定目录"
exit(0)
fi

desfile=$1
#setline 指定从倒数第几行开始插入操作(可以自行设定指定倒数的行数)
setline=$2
srcfile=$3

#设定文档行数遍历标记
lineidx=0

#读取文档的总行数
maxline=0
cat ${desfile}|wc -l|read maxline

#初始化中间文档,备份源文档
cp ./${desfile} ./${desfile}.bak
echo "\c">./lineltset.txt
echo "\c">./linegeset.txt
echo "\c">./tmp.txt

[ $maxline -lt $setline ] && echo "行数小于指定行: $setline,无法执行,退出"&&exit(1);
locidx=`expr $maxline - $setline `

#分割待处理的文档(按照指定行分割)
cat ${desfile}|while read strline
do
[ $lineidx -lt $locidx ] && echo ${strline}>>./lineltset.txt && continue
[ $lineidx -ge $locidx ] && echo ${strline}>>./linegeset.txt && continue
lineidx=`expr $lineidx + 1 `
done

#生成最终文档
cat lineltset.txt>>tmp.txt
cat ${srcfile}>>tmp.txt
cat linegeset.txt>>tmp.txt
mv ./tmp.txt ./${desfile}

#删除中间文档
rm ./lineltset.txt
rm ./linegeset.txt
rm ./tmp.txt

echo "处理结束"

回答2:

提供两个方法吧:
[seesea2517@localhost] $ str="你要添加的内容"
[seesea2517@localhost] $ li=[seesea2517@localhost] $(wc -l a.txt | cut -d " " -f 1); sed -e ''"[seesea2517@localhost] ${li}"'i '"[seesea2517@localhost] $str"'' a.txt
1
2
3
4
5
你要添加的内容
6
7
[seesea2517@localhost] $ awk -v str="[seesea2517@localhost] $str" '{ar[i++]=[seesea2517@localhost] $0;} END{for (j=0; j < i; ++j) {if(j == (i - 4)){
print str;}print ar[j];}}' a.txt
1
2
3
你要添加的内容
4
5
6
7