Замена спецификатора данных в двойных кавычках с использованием sed, awk или perl - PullRequest
0 голосов
/ 09 сентября 2018

У меня есть текстовый файл с | разделителем и " квалификатором. Я хотел бы изменить квалификатор на символ ~, проблема, с которой я сталкиваюсь, заключается в том, что текст фактического значения столбца имеет двойные кавычки.

Мне нужно изменить классификатор, не удаляя двойные кавычки в значениях столбца. Я предоставил образец одной записи:

"Live Your Dreams: Be You"|"20 Feb 2018"|"2 formats and editions"|"Are you being swept away by life being busy? Are things seemingly out of your control? Do you want to calm the chaos in your life? Are you ready to transform your life? In 
"Live Your Dreams"
now AMAZON BESTSELLER, readers are shown how to take immediate control of their mental, emotional, physical and entrepreneurial destiny."|"All this and more as you immerse yourself in the story that opens up like scenes from "a Bollywood movie""|"Indian Edition"

Я уже пробовал с sed и awk, ссылаясь на содержимое в переполнении стека и unix.com, но двойные кавычки внутри столбца создают проблемы.

Желаемый вывод:

~Live Your Dreams: Be You~|~20 Feb 2018~|~2 formats and editions~|~Are you being swept away by life being busy? Are things seemingly out of your control? Do you want to calm the chaos in your life? Are you ready to transform your life? In 
"Live Your Dreams"
now AMAZON BESTSELLER, readers are shown how to take immediate control of their mental, emotional, physical and entrepreneurial destiny.~|~All this and more as you immerse yourself in the story that opens up like scenes from "a Bollywood movie"~|~Indian Edition~

Код пробовал: sed 's _ "([^ *])" _ ~ \ 1 ~ _g' data.txt> tdata.txt

Результаты в соответствии с вышеуказанным sed:

"Live Your Dreams: Be You~|~20 Feb 2018~|~2 formats and editions~|~Are you being swept away by life being busy? Are things seemingly out of your control? Do you want to calm the chaos in your life? Are you ready to transform your life? In 
"Live Your Dreams"
now AMAZON BESTSELLER, readers are shown how to take immediate control of their mental, emotional, physical and entrepreneurial destiny.~|~All this and more as you immerse yourself in the story that opens up like scenes from "a Bollywood movie"~|~Indian Edition~

Любая помощь со скриптом awk или sed или Perl будет очень признательна.

Заранее спасибо, Прабху

Ответы [ 2 ]

0 голосов
/ 09 сентября 2018

На самом деле у вас есть неверно сформированные данные CSV, где символ разделителя равен |.

Это неправильно сформировано, потому что "внутренние" кавычки не экранированы: в CSV-поле, которое содержит кавычки, кавычки должны быть продублированы, как это

1,2,"field,with,commas","this field ""contains quotes"" that are duplicated"
# ..................................^^...............^^

Если возможно исправить ваши входные данные, чтобы они выглядели так:

"Live Your Dreams: Be You"|"20 Feb 2018"|"2 formats and editions"|"Are you being swept away by life being busy? Are things seemingly out of your control? Do you want to calm the chaos in your life? Are you ready to transform your life? In 
""Live Your Dreams""
now AMAZON BESTSELLER, readers are shown how to take immediate control of their mental, emotional, physical and entrepreneurial destiny."|"All this and more as you immerse yourself in the story that opens up like scenes from ""a Bollywood movie"""|"Indian Edition"

если внутренние кавычки в строках 2 и 3 правильно экранированы, то вы можете использовать анализатор CSV для преобразования выходных кавычек. Синтаксический анализатор Perl csv может обрабатывать поля, содержащие символы новой строки:

perl -MText::CSV -e '
    open my $fh, "<:encoding(UTF-8)", shift(@ARGV);
    my $csv_in = Text::CSV->new({ quote_char => "\"", sep_char => "|", binary => 1 });
    my $csv_out = Text::CSV->new({ quote_char => "~", escape_char => "~", sep => "|", binary => 1 });
    while (my $row = $csv_in->getline($fh)) {
        $csv_out->say(STDOUT, $row);
    }
    $csv_in->eof or $csv_in->error_diag();
' file.csv
~Live Your Dreams: Be You~|~20 Feb 2018~|~2 formats and editions~|~Are you being swept away by life being busy? Are things seemingly out of your control? Do you want to calm the chaos in your life? Are you ready to transform your life? In 
"Live Your Dreams"
now AMAZON BESTSELLER, readers are shown how to take immediate control of their mental, emotional, physical and entrepreneurial destiny.~|~All this and more as you immerse yourself in the story that opens up like scenes from "a Bollywood movie"~|~Indian Edition~
0 голосов
/ 09 сентября 2018

В Perl вы можете попробовать эту строку:

perl -anF'\|' -E 'for (@F) {s/^"/~/;s/"$/~/} print join "|", @F' file.txt

Это разделит каждую строку на |, а затем заменит " в начале или конце каждого поля на ~.

Согласно новой информации в комментариях: Если вы хотите оставить строки с одним столбцом (полем) без изменений:

perl -anF'\|' -E 'if (@F == 1) {print; next} for (@F) {s/^"/~/;s/"$/~/} print join "|", @F' file.txt
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...