如何使用python或其他工具替换文件的第一行?

时间:2018-11-06 08:07:10

标签: python sed replace

我有一个名为hanlp.properties的文件:

root=/Users/pan/Documents
other content

我想传递参数“ / User / a / b”并替换根路径

root=/User/a/b
other content

/User/a/b是一个参数。

如何通过使用python或任何其他工具实现该目标?

5 个答案:

答案 0 :(得分:1)

使用Python 3:

import argparse

from sys import exit

from os.path import getsize

# collect command line arguments
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--parameter', required=True, type=str)
parser.add_argument('-f', '--file', required=True, type=str)
args = parser.parse_args()

# check if file is empty
if getsize(args.file) == 0:
    print('Error: %s is empty' % args.file)
    exit(1)

# collect all lines first
lines = []
with open(args.file) as file:
    first_line = next(file)

    # Check if '=' sign exists in first line
    if '=' not in first_line:
        print('Error: first line is invalid')
        exit(1)

    # split first line and append new line
    root, parameter = first_line.split('=')
    lines.append('%s=%s\n' % (root, args.parameter))

    # append rest of lines normally
    for line in file:
        lines.append(line)

# rewrite new lines back to file
with open(args.file, 'w') as out:
    for line in lines:
        out.write(line)

其工作方式如下:

$ cat hanlp.properties
root=/Users/pan/Documents
other content
$ python3 script.py --file hanlp.properties --parameter /Users/a/b
$ cat hanlp.properties
root=/User/a/b
other content

答案 1 :(得分:0)

编辑: ,因为OP更改了要求,所以现在也添加了此解决方案。使用GNU awk进行了测试。如果要将输出保存到Input_file本身,请附加> temp_file && mv temp_file Input_file

awk -F'=' 'FNR==NR{if($0~/root/){value=$2};nextfile} /root/{$2=value} 1' OFS="=" parameter_file  Input_file

说明: 也在此处添加了上述代码的说明。

awk -F'=' '                           ##Mentioning field separator as = here for all lines of all mentioned passed Input_files to awk.
FNR==NR{                              ##Checking condition FNR==NR which will be TRUE when parameter_file is being read.
  if($0~/root/){                      ##Checking if a line has root string in it then do following.
    value=$2                          ##Assigning value of $2 to variable value here.
  }
  nextfile                            ##nextfile will jump to next passed Input_file and all further lines for parameter file will be skipped.
}
/root/{                               ##Checking if a line has string root in it then do following.
  $2=value                            ##Setting 2nd field value as value variable here.
}
1                                     ##By mentioning 1 telling awk to print edited/no-edited lines here.
' OFS="=" parameter_file  Input_file  ##Mentioning OFS value as = here and mentioning Input_file(s) name here.


它应该是简单的sed程序。如果您要将输出保存到Input_file本身,请使用sed -i选项。

sed '/root=/s/path1/path2/' Input_file

如果您想使用awk,那么下面的内容可能会对您有所帮助。

awk '/root=/{sub("path1","path2")} 1' Input_file > temp_file && mv temp_file Input_file

答案 2 :(得分:0)

这可能会对您有所帮助。

rs = np.linspace(0, pi/2, 1000)
t0 = 0.0 #the initial condition
ts = odeint(dt_dr, t0, rs)

plt.rcParams.update({'font.size': 11})
plt.xlabel("t")
plt.ylabel("r")
plt.plot(ts, rs)

# Change axis limits
plt.ylim(0,0.6)
plt.xlim(-1.5,1.5)

# Move left spine to x=0
ax = plt.gca()
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')

plt.show()

答案 3 :(得分:0)

我写一个shell a.sh

if [ ! -n "$1" ] ;then
   echo "Please input hanlp data path!"
else
   echo "The hanlp data path you input is $1"
   var="root="
   path=$var$1
   sed -i '/^root/c'$path'' hanlp.properties
fi

然后

 chmod 777 a.sh

运行:

./a.sh /User/a/b

答案 4 :(得分:0)

从HanLP v1.7开始,您可以使用除配置文件以外的许多方法来设置根目录。请参见this issue,您可能需要Google翻译。