python으로 파일 내용 변경방법?

high385의 이미지

파일에 다음과 같은 내용이 있다고 할때 변경법질문입니다
1st file 내용
aa=446
a= bcd
b= [fgh]
c= [jfr
dfgh
dghhy]
gg=678

2nd파일 내용
a= cd
b= [fh]
c= [jf
dfg
dhy]

와 같을때 1st파일의 내용에서 2nd파일의 내용으로 변경시 python,dos, perl,sed 등으로 파일 내용을 하고싶은데 변경은 어떻게하는게 좋을까요?

윈도우 환경에서 작업하는것인데요

python의 re모듈을 이용한 search sub등을 활용하는방법을 생각해보았는데 아직 어렵네요

혹시 위와 같은 상황에서 c코딩방식이 아닌
스크립트방식으로 파일 변경 쉽게해주는 방법 있으려나요?

언어는 상관없고 윈도우 환경에서 일괄 변경해주는 방법이 있나 궁금합니다

세벌의 이미지

변경 규칙이 무엇인가요?
코딩 말고 글로 설명해 주셔요.

high385의 이미지

2nd file의 내용을 1st 파일로 대체시의 규칙
==>
1st file 내용
aa=446
a= bcd
b= [fgh]
c= [jfr
dfgh
dghhy]
gg=678

2nd파일 내용
a= cd
b= [fh]
c= [jf
dfg
dhy]
==>
=을 기준으로 key=value가 됩니다.
key를 기준으로 검색이 됩니다.
key는 두 파일 모두 유일한 값입니다.
key를 기준으로 특정 string이 검색이된다면 2nd file의 vale를 1st file의 vale 대신 사용합니다.

key는 한줄에 적혀있지만
value는 배열일 경우 2줄 이상일 수 있습니다.
c= [jf
dfg
dhy] 에서
value는 3줄이 되며
[jf
dfg
dhy] 이 value가 됩니다.

raymundo의 이미지

1) 1번 파일의 키-값 중에 2번 파일에 같은 키가 있으면 덮어쓴다
2) 1번 파일의 키-값 중에 2번 파일에 없는 것은? 그냥 놔두는 걸로 가정
3) 1번 파일에 없는 키가 2번 파일에 나오면? 추가하는 걸로 가정

use strict;
use warnings;
use 5.010;
 
# 키-값이 저장될 해시
my %hash;
# 값이 여러줄에 있는 경우를 대비해서, 현재 읽고 있는 키가 뭔지 보관
my $current_key;
# 키의 배열. 딱히 필요는 없지만 이왕이면 파일에 나온 순서대로 출력할 수 있게
my @keys;
 
while (my $line = <>) {
    chomp $line;;
    next if $line =~ /^\s*$/;   # 빈 줄 무시
 
    if ( $line =~ /^(.+)=(.+)$/ ) {
        # 키=값인 줄이 나오면 새 키에 값 저장
        $current_key = $1;
        push @keys, $current_key unless exists $hash{$current_key};
        $hash{$current_key} = $2;
    }
    else {
        # 그렇지 않은 줄이면 가장 최근 키의 값에 덧붙임
        $hash{$current_key} .= "\n".$line;
    }
}
 
foreach my $key ( @keys ) {
    print $key, "=", $hash{$key}, "\n";
}

$ perl t.pl a.txt b.txt
aa=446
a= cd
b= [fh]
c= [jf
dfg
dhy]
gg=678

좋은 하루 되세요!

anony999의 이미지

bash 버전.. 윈도우 환경이니 cygwin 이나 win-bash, gnuwin32 등 bash 와 sed 있으면 될 겁니다.
- 배열(multi-line)은 반드시 [] 로 감싸 있다고 가정.

$ cat run.sh
#!/bin/bash
 
until [ -z "$1" ]; do
        cat $1 | sed 's/[[:space:]]*=[[:space:]]*/=/g' | sed -e 's/\[/"[/g' -e 's/\]/]"/g' > $1.out
        source $1.out
        shift
done
 
keylist=$(cat *.out | grep = | cut -d= -f1 | sort -u)
for key in $keylist; do
        echo "$key = $(eval echo \"\$$key\")"
done
 
exit 0;
 
$ bash run.sh 1st.txt 2nd.txt
a = cd
aa = 446
b = [fh]
c = [jf
dfg
dhy]
gg = 678

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.