M
M
MaximVo2017-09-25 13:13:20
Perl
MaximVo, 2017-09-25 13:13:20

How to get new lines from a text file?

There is a master.txt with the content:
a
b
c
There is a file.txt with the content:
c
d
e
How to save the lines:
d
e
To a new.txt file and also create a newmaster.txt file with the content
a
b
c
d
e

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey, 2017-09-25
@AlexMaxTM

Well, at least add one more tag besides Windows. Doing it quickly and easily in Windows without using other tools is very difficult. This can be done in Total Commander by comparing two files, you can use notepad++. but the easiest way is to write a script (it's just a few lines of code). For me, the easiest way to do this is with perl (I have it on Windows). But I can do it in some other languages ​​too.

I
Ilya33, 2017-09-25
@Ilya33

for perl I quickly sketched:

use strict;
use warnings;

use Array::Utils qw(:all);


open(my $fh_m, '<', 'master.txt') or
    die "Не смог открыть файл :(";
open(my $fh_f, '<', 'file.txt') or
    die "Не смог открыть файл :(";

open(my $fh_n, '>', 'new.txt') or
    die "Не смог открыть файл :(";
open(my $fh_nm, '>', 'newmaster.txt') or
    die "Не смог открыть файл :(";

my @m = map {s/\r?\n?$//r} <$fh_m>;
my @f = map {s/\r?\n?$//r} <$fh_f>;

my @diff = array_minus(@f, @m);

foreach(@m) {
    print $fh_nm "$_\n";
}

foreach(@diff) {
    print $fh_n "$_\n";
    print $fh_nm "$_\n";
}

perl for windows can be taken from here or from here

A
ArtemZA, 2017-09-25
@ArtemZA

in Python

first = 'master.txt'
second = 'file.txt'
directory = 'C:\\new\\'

A = []
B = []
C = []
D = []


def FileRead(file):
    f = open(directory + file , 'r' , encoding = "utf-8")
    for i in f:
        if q == 0:
            A.append(i)
        if q == 1:
            B.append(i)
    f.close()
   
def FileWrite(file,spisok):
    f = open(directory + file , 'w')
    for line in spisok:
        f.write(line + '\n')
    f.close()
        
  
for q in range(0,2):
    if q == 0:
        FileRead(first)
    if q == 1:
        FileRead(second)

A = [line.rstrip() for line in A]
B = [line.rstrip() for line in B]
for i in A:
    if not i in B:
        print(i)
        C.append(i)

for i in B:
    if i in A:
        print(i)
        C.append(i)

for i in B:
    if not i in A:
        print(i)
        C.append(i)
        D.append(i)

FileWrite('newmaster.txt', D)
FileWrite('new.txt',C)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question