怎么通过你shell脚本删除文件的某一行以及后面几行

如题所述

1、启动Linux系统,用.sh工具(xshell或者SecureCRT等)连上Linux系统。

2、在shell脚本启动时或者在脚本内都可以添加这些调试选项。测试脚本debug.sh,代码如图所示。

3、在脚本启动时添加调试选项。来调试debug.sh,可以在启动脚本时,输入以下命令:bash -x  ./debug.sh 或者  sh -x ./debug.sh。

4、使用set 命令。例如要开启-x选项,则在脚本内容中添加命令:set -x set +x 是关闭调试。

5、要看debug.sh脚本执行的信息,就不需要使用bash -x  ./debug.sh执行了。直接./debug.sh 就可以看到修改后的信息了,这样就完成了

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-11-27
#!/bin/sh
myfile=test.txt
startLine=3
lineCnt=4
let endLine="startLine + lineCnt - 1"
sed -i $startLine','$endLine'd' $myfile

startLine 表示开始行的行号

lineCnt 表示总共要删除的行数

追问

能否不固定到行号,比如我要删除带adc字符串的某一行以及后面4行,该怎么写,谢谢

追答#!/bin/sh
myfile=test.txt
startLine=`sed -n '/adc/=' $myfile` #先计算带adc字符串行的行号
lineAfter=4
let endLine="startLine + lineAfter"
sed -i $startLine','$endLine'd' $myfile

或者:

#!/bin/sh
myfile=test.txt
lineAfter=4
awk -v n=$lineAfter '{if($0~/adc/)for(i=1;i<=n+1;i++)getline;print}' $myfile >tmp
mv -f tmp $myfile

追问

非常感谢你的热心回答,但是现在遇到连一个问题,加入文件中有几行都含有adc字符,我只想得到含有adc字符的最后一行的行号,该怎么弄

追答startLine=`sed -n '/adc/=' $myfile | tail -n1`

用 tail 取最后一个行号。

也可以用awk。

awk '/adc/{n=NR}END{print n}' $myfile

本回答被网友采纳
相似回答