shell通过调用python函数完成文件操作

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,来处理别的目录文件。

注意点:

  1. shell向py传参,参数带空格的处理,利用“参数”
  2. 不同目录,利用绝对路径
  3. 在notepad++等windows下的tab,处理linux下的文件不对,这种输入最好是在vim中。
  4. py中接受参数:sys.argv[]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值