shell脚本:对指定文件的指定行新增一行指定的字符串。字符串里面有特殊符号,sed实现总是出问题,利用python实现。
#!/bin/bash
echo "shell begin"
PY_PATH=${PWD}
cd ../config/
#filename="test"
#fileno=38
#new_str="source /bin/bash/XXXXXXX/Kconfig"
filename="Makefile"
fileno=3
new_str=' LINE4 \'
echo ${filename}
echo ${fileno}
echo ${new_str}
python ${PY_PATH}/for_shell.py "${filename}" "${fileno}" "${new_str}"
for_shell.py
# add message in lineno
# change message in target str
import sys
filename = sys.argv[1]
lineno = sys.argv[2]
new_str = sys.argv[3]
print(filename)
print(lineno)
print(new_str)
def add_str(filename, lineno, new_str):
print("add_str begin")
new_str=new_str+"\n"
lines=[]
f=open(filename,'r')
for line in f:
lines.append(line)
f.close()
lines.insert(lineno, new_str)
s=''.join(lines)
f=open(filename,'w+')
f.write(s)
f.close()
del lines[:]
print("add_str end")
add_str(filename, int(lineno), new_str)
一些注释在py里,调用会出错
# new_str = "source /bin/bash/sl8521-test/Kconfig"+"\n"
# add_str("test", 31, new_str)
# new_str = "config:TARGET_XXXX"+"\n"+"\t"+"this a config"+"\n"+"\t"+"this is a test"+"\n"+"\t"+"help message"+"\n"+" "+"\n"
# add_str("test", 10, new_str)
# 所以不要找到整体的5行,而是只找到一行,后续的自己去写。!!!
# 找到config:TARGET_XXXX即可.
# all like this
# 关于shell中调用python,并且在不同的目录执行函数。
# 0405/mypy.py和myshell.sh
# 利用shell调用同级目录下的py,来处理别的目录文件。
注意点:
- shell向py传参,参数带空格的处理,利用“参数”
- 不同目录,利用绝对路径
- 在notepad++等windows下的tab,处理linux下的文件不对,这种输入最好是在vim中。
- py中接受参数:sys.argv[]