【问题标题】:how to replace first line of a file using python or other tools?如何使用 python 或其他工具替换文件的第一行?
【发布时间】:2019-04-09 14:44:00
【问题描述】:

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

root=/Users/pan/Documents
other content

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

root=/User/a/b
other content

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

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

【问题讨论】:

  • 请在您的帖子中添加预期的输出,代码标签不清楚。
  • 我变了。@RavinderSingh13
  • 始终加入您为解决问题而付出的努力,因为我们都在这里学习。

标签: python sed replace


【解决方案1】:

编辑: 因为 OP 改变了要求,所以现在也添加这个解决方案。用 GNU awk 对此进行了测试。附加 > temp_file && mv temp_file Input_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

【讨论】:

  • path1 是可变的
  • @YaoPan,你想作为参数从脚本发送吗?请详细说明这一点。
  • 对不起,我没有详细描述,我改了
  • @YaoPan,请查看 m EDIT 解决方案,然后告诉我?
【解决方案2】:

使用 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

【讨论】:

    【解决方案3】:

    这可能会对你有所帮助。

    import os
    infile=os.path.join(os.getcwd(),"text.txt")
    data = open(infile).readlines()
    print(data)
    data[0] = 'new content of;lkdsajv;ldsahbv;ikj'+'\n'
    print(data)
    with open(infile, 'w') as fw:
        fw.writelines(data)
    

    【讨论】:

      【解决方案4】:

      我写了一个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
      

      【讨论】:

        【解决方案5】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-03-24
          • 2016-03-13
          • 2017-11-09
          • 2018-08-05
          相关资源
          最近更新 更多