Как обернуть текст в многострочную таблицу, не теряя форматирование? - PullRequest
1 голос
/ 16 марта 2019

У меня есть данные (в основном журналы, но также и заметки пользователя) в виде:

[2019_03_10][21:12:55] # Very useful text of hight iportance to demonstrate my question.
[2019_03_10][22:32:55] #  Another Text.
[2019_03_10][23:02:22] #  blablabal Bla bla, just another long text with linebreak. And this one is just a little longer then those before.

На данный момент я использую cat test.txt | column -s '#' -t, и вот что я получаю:

[2019_03_10][21:12:55]   Very useful text of hight iportance 
to demonstrate my question. 
[2019_03_10][22:32:55]    Another Text.
[2019_03_10][23:02:22]    blablabal Bla bla, just another lon
g text with linebreak. And this one is just a little longer t
hen those before.

Вот что я хотел бы получить:

[2019_03_10][21:12:55]   Very useful text of hight iportance 
                          to demonstrate my question. 
[2019_03_10][22:32:55]    Another Text.
[2019_03_10][23:02:22]    blablabal Bla bla, just another lon
                          g text with linebreak. And this one 
                          is just a little longer then those 
                          before.

Должен быть простой способ сделать это.Не должен?

Ответы [ 5 ]

0 голосов
/ 17 марта 2019

Я бы воспользовался командой UNIX fold, поэтому вам не нужно заново изобретать колесо:

$ cat tst.awk
{
    beg = end = $0
    sub(/ *#.*/,"",beg)
    sub(/[^#]+# */,"",end)

    cmd = "printf \047" end "\n\047 | fold -sw38"
    while ( (cmd | getline line) > 0 ) {
        print beg, line
        gsub(/./," ",beg)
    }
}

$ awk -f tst.awk file
[2019_03_10][21:12:55] Very useful text of hight iportance
                       to demonstrate my question.
[2019_03_10][22:32:55] Another Text.
[2019_03_10][23:02:22] blablabal Bla bla, just another long
                       text with linebreak. And this one is
                       just a little longer then those
                       before.
0 голосов
/ 17 марта 2019

Это, похоже, работа для :

Этот первый скрипт ответит на ваш вопрос, разделив строки на символ 60 (без учета пробелов ).

sed ':a;s/\([^\n]\{60\}\)\([^\n]\+\)/\1\n                       \2/;ta'

Будет выводить что-то вроде:

[2019_03_10][21:12:55] # Very useful text of hight importanc
                       e to demonstrate my question.
[2019_03_10][22:32:55] Another Text.
[2019_03_10][23:02:22] blablabal Bla bla, just another long 
                       text with linebreak. And this one is 
                       just a lot longer than those before, 
                       by adding unsignificant and useless b
                       la bla.

Кажется, но разделение слов:

sed ':a;/.\{61\}/s/\([^\n]\{1,60\}\) \([^\n]\+\)/\1\n                       \2/;/\n/!bb;P;D;:b;ta'

или

sed '
    :a;
    /.\{61\}/s/\([^\n]\{1,60\}\) \([^\n]\+\)/\1\n                       \2/;
    /\n/!bb;
    P;
    D;
    :b;
    ta
'

будет отображать:

[2019_03_10][21:12:55] # Very useful text of hight
                       importance to demonstrate my
                       question.
[2019_03_10][22:32:55] Another Text.
[2019_03_10][23:02:22] blablabal Bla bla, just another long
                       text with linebreak. And this one is
                       just a lot longer then those before,
                       by adding unsignificant and useless
                       bla bla.
0 голосов
/ 16 марта 2019

Вы можете попробовать следующий скрипт:

#!/bin/bash
WIDTH=50                                    # width of column2 
# TMPFILE=$(mktemp)                         # tempfile in /tmp
TMPFILE=$(mktemp -p /dev/shm)               # tempfile in shared memory
while read line; do                         # read all lines from log
    column1=${line%%#*}                     # extract column1
    blank=${column1//?/ }                   # blankline, size len(column1)
    column2=${line##*#}                     # column2, comments
    echo $column2 | fmt -$WIDTH > $TMPFILE  # format column2
    while read line2; do                    # read new formated lines
        echo  "$column1" $line2             # write column1 and column2
        column1=$blank                      # blank column1
    done < $TMPFILE                         # read from tempfile
done < "$1"                                 # first arg from commandline
rm $TMPFILE                                 # delete tempfile

ИСПОЛЬЗОВАНИЕ: имя файла сценария

Если у вас нет общей памяти, вы можете заменить строку 4 строкой 3.

0 голосов
/ 16 марта 2019

Использование командной строки Perl. Вы можете изменить 20 на 30 или 40, чтобы обернуть нужную вам длину.

$ perl -ne ' ($x,$y)=/(.+?)#(.+)/ ; print "$x"; $s=""; 
   while($y=~/(.{20,}?\s|.*$)/g) { printf("%s%s\n",$s,$1);$s="\t\t\t" } ' mac.txt
[2019_03_10][21:12:55]  Very useful text of
                        hight iportance to demonstrate
                        my question.

[2019_03_10][22:32:55]  Another Text.

[2019_03_10][23:02:22]  blablabal Bla bla, just
                        another long text with
                        linebreak. And this one
                        is just a little longer
                        then those before.


$

Есть дополнительный символ новой строки, если вы хотите удалить

$ perl -lne ' ($x,$y)=/(.+?)#(.+)/ ; printf("%s",$x); $s=""; 
   while($y=~/(.{20,}?\s|.*$)/g) { $p=$1; print $s,$p if $p!~/^\s*$/s; $s="\t\t\t" } ' mac.txt
[2019_03_10][21:12:55]  Very useful text of
                        hight iportance to demonstrate
                        my question.
[2019_03_10][22:32:55]  Another Text.
[2019_03_10][23:02:22]  blablabal Bla bla, just
                        another long text with
                        linebreak. And this one
                        is just a little longer
                        then those before.

$
0 голосов
/ 16 марта 2019

Perl-скрипт, использующий стандартный Text :: Wrap модуль:

#!/usr/bin/perl
use strict;
use warnings;
use feature qw/say/;
use Text::Wrap;

while (<>) {
  chomp;
  my $line = wrap("", "\t\t\t", $_);
  $line =~ s/ # /\t/;
  say $line;
}

Использование:

$ perl wrap.pl test.txt
[2019_03_10][21:12:55]  Very useful text of hight iportance to demonstrate
                        my question.

Версия с одним вкладышем:

$ perl -MText::Wrap -lpe '$_ = wrap("", "\t\t\t", $_); s/ # /\t/;' test.txt
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...