Подтвердить что ты не робот

Разделить один файл на несколько файлов на основе разделителя

У меня есть один файл с -| как разделитель после каждого раздела... нужно создать отдельные файлы для каждого раздела с помощью unix.

пример входного файла

wertretr
ewretrtret
1212132323
000232
-|
ereteertetet
232434234
erewesdfsfsfs
0234342343
-|
jdhg3875jdfsgfd
sjdhfdbfjds
347674657435
-|

Ожидаемый результат в файле 1

wertretr
ewretrtret
1212132323
000232
-|

Ожидаемый результат в файле 2

ereteertetet
232434234
erewesdfsfsfs
0234342343
-|

Ожидаемый результат в файле 3

jdhg3875jdfsgfd
sjdhfdbfjds
347674657435
-|
4b9b3361

Ответ 1

Один лайнер, без программирования. (за исключением регулярного выражения и т.д.)

csplit --digits=2  --quiet --prefix=outfile infile "/-|/+1" "{*}"

Ответ 2

awk '{print $0 " -|"> "file" NR}' RS='-\\|'  input-file

Ответ 3

Debian имеет csplit, но я не знаю, является ли это общим для всех/большинства/других дистрибутивов. Если нет, то не должно быть слишком сложно отследить источник и скомпилировать его...

Ответ 4

Я решил немного другую проблему, в которой файл содержит строку с именем, в котором должен следовать следующий текст. Этот код perl делает трюк для меня:

#!/path/to/perl -w

#comment the line below for UNIX systems
use Win32::Clipboard;

# Get command line flags

#print ($#ARGV, "\n");
if($#ARGV == 0) {
    print STDERR "usage: ncsplit.pl --mff -- filename.txt [...] \n\nNote that no space is allowed between the '--' and the related parameter.\n\nThe mff is found on a line followed by a filename.  All of the contents of filename.txt are written to that file until another mff is found.\n";
    exit;
}

# this package sets the ARGV count variable to -1;

use Getopt::Long;
my $mff = "";
GetOptions('mff' => \$mff);

# set a default $mff variable
if ($mff eq "") {$mff = "-#-"};
print ("using file switch=", $mff, "\n\n");

while($_ = shift @ARGV) {
    if(-f "$_") {
    push @filelist, $_;
    } 
}

# Could be more than one file name on the command line, 
# but this version throws away the subsequent ones.

$readfile = $filelist[0];

open SOURCEFILE, "<$readfile" or die "File not found...\n\n";
#print SOURCEFILE;

while (<SOURCEFILE>) {
  /^$mff (.*$)/o;
    $outname = $1;
#   print $outname;
#   print "right is: $1 \n";

if (/^$mff /) {

    open OUTFILE, ">$outname" ;
    print "opened $outname\n";
    }
    else {print OUTFILE "$_"};
  }

Ответ 5

Вы также можете использовать awk. Я не очень хорошо знаком с awk, но следующее, похоже, работает для меня. Он сгенерировал файлы part1.txt, part2.txt, part3.txt и part4.txt. Обратите внимание, что последний файл partn.txt, который он генерирует, пуст. Я не уверен, как это исправить, но я уверен, что это можно сделать с небольшой настройкой. Любые предложения кто-нибудь?

Файл awk_pattern:

BEGIN{ fn = "part1.txt"; n = 1 }
{
   print > fn
   if (substr($0,1,2) == "-|") {
       close (fn)
       n++
       fn = "part" n ".txt"
   }
}

bash команда:

awk -f awk_pattern input.file

Ответ 6

Здесь находится Python 3 script, который разбивает файл на несколько файлов на основе имени файла, предоставленного разделителями. Пример входного файла:

# Ignored

######## FILTER BEGIN foo.conf
This goes in foo.conf.
######## FILTER END

# Ignored

######## FILTER BEGIN bar.conf
This goes in bar.conf.
######## FILTER END

Здесь script:

#!/usr/bin/env python3

import os
import argparse

# global settings
start_delimiter = '######## FILTER BEGIN'
end_delimiter = '######## FILTER END'

# parse command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input-file", required=True, help="input filename")
parser.add_argument("-o", "--output-dir", required=True, help="output directory")

args = parser.parse_args()

# read the input file
with open(args.input_file, 'r') as input_file:
    input_data = input_file.read()

# iterate through the input data by line
input_lines = input_data.splitlines()
while input_lines:
    # discard lines until the next start delimiter
    while input_lines and not input_lines[0].startswith(start_delimiter):
        input_lines.pop(0)

    # corner case: no delimiter found and no more lines left
    if not input_lines:
        break

    # extract the output filename from the start delimiter
    output_filename = input_lines.pop(0).replace(start_delimiter, "").strip()
    output_path = os.path.join(args.output_dir, output_filename)

    # open the output file
    print("extracting file: {0}".format(output_path))
    with open(output_path, 'w') as output_file:
        # while we have lines left and they don't match the end delimiter
        while input_lines and not input_lines[0].startswith(end_delimiter):
            output_file.write("{0}\n".format(input_lines.pop(0)))

        # remove end delimiter if present
        if not input_lines:
            input_lines.pop(0)

Наконец, как вы его запускаете:

$ python3 script.py -i input-file.txt -o ./output-folder/

Ответ 7

cat file| ( I=0; echo -n "">file0; while read line; do echo $line >> file$I; if [ "$line" == '-|' ]; then I=$[I+1]; echo -n "" > file$I; fi; done )

и форматированный вариант:

#!/bin/bash
cat FILE | (
  I=0;
  echo -n"">file0;
  while read line; 
  do
    echo $line >> file$I;
    if [ "$line" == '-|' ];
    then I=$[I+1];
      echo -n "" > file$I;
    fi;
  done;
)

Ответ 8

Следующая команда работает для меня. Надеюсь, поможет. bash awk 'BEGIN{file = 0; filename = "output_" file ".txt"} /-|/ {getline; file ++; filename = "output_" file ".txt"}{print $0 > filename}' input

Ответ 9

Используйте csplit, если он у вас есть.

Если вы этого не сделаете, но у вас есть Python... не используйте Perl.

Предполагая, что ваш файл образца называется "samplein":

$ python -c "import sys
for i, c in enumerate(sys.stdin.read().split('-|')):
    open(f'out{i}', 'w').write(c)" < samplein

Если у вас есть Python 3.5 или ниже, вы не можете использовать f-строки:

$ python -c "import sys
for i, c in enumerate(sys.stdin.read().split('-|')):
    open('out' + str(i), 'w').write(c)" < samplein

и теперь:

$ ls out*
out0  out1  out2  out3

Ответ 10

Вот код perl, который будет делать

#!/usr/bin/perl
open(FI,"file.txt") or die "Input file not found";
$cur=0;
open(FO,">res.$cur.txt") or die "Cannot open output file $cur";
while(<FI>)
{
    print FO $_;
    if(/^-\|/)
    {
        close(FO);
        $cur++;
        open(FO,">res.$cur.txt") or die "Cannot open output file $cur"
    }
}
close(FO);

Ответ 11

Это та проблема, которую я написал для контекстного разделения: http://stromberg.dnsalias.org/~strombrg/context-split.html

$ ./context-split -h
usage:
./context-split [-s separator] [-n name] [-z length]
        -s specifies what regex should separate output files
        -n specifies how output files are named (default: numeric
        -z specifies how long numbered filenames (if any) should be
        -i include line containing separator in output files
        operations are always performed on stdin