【问题标题】:Find if null exists in csv file查找csv文件中是否存在null
【发布时间】:2017-10-26 05:24:19
【问题描述】:

我有一个 csv 文件。该文件有一些异常,因为它包含一些未知字符。

这些字符出现在流行编辑器的第 1535 行(图片附在下面)。此行的终端中的 sed 命令不显示任何内容。

$ sed '1535!d' sample.csv
"sample_id","sample_column_text_1","sample_"sample_id","sample_column_text_1","sample_column_text_2","sample_column_text_3"

但下面是各种编辑器中文件的快照。

崇高文本

纳米

该目录具有包含此字符/字符链的各种 csv 文件。

我需要编写一个 bash 脚本来确定具有此类字符的文件。我怎样才能做到这一点?

【问题讨论】:

  • 您可以使用grep '[^[:print:]]' 查找包含不可打印字符的文件或行。
  • 这个命令卡在我的终端上……没有前进。这个命令有什么作用以及它是如何工作的?

标签: bash csv sed null


【解决方案1】:

你可以试试tr

grep '\000' filename to find if the files contain the \000 characters.

您可以使用它来删除 NULL 并使其成为非 NULL 文件: tr < file-with-nulls -d '\000' > file-without-nulls

【讨论】:

    【解决方案2】:

    以下来自;

    http://www.linuxquestions.org/questions/programming-9/how-to-check-for-null-characters-in-file-509377/

    #!/usr/bin/perl -w
    
    use strict;
    
    my $null_found = 0;
    
    foreach my $file (@ARGV) {
        if ( ! open(F, "<$file") ) {
            warn "couldn't open $file for reading: $!\n";
            next;
        }
    
        while(<F>) {
            if ( /\000/ ) {
                print "detected NULL at line $. in file $file\n";
                $null_found = 1;
                last;
            }
        }
        close(F);
    }
    
    exit $null_found;
    

    如果它可以正常工作,您可以将其保存到文件 nullcheck.pl 并使其可执行;

    chmod +x nullcheck.pl
    

    它似乎将一组文件名作为输入,但如果找到任何文件名都会失败,所以我一次只传入一个。下面的命令用于运行脚本。

    for f in $(find . -type f -exec grep -Iq . {} \; -and -print) ; do perl ./nullcheck.pl $f || echo "$f has nulls"; done
    

    上面的find命令是从Linux command: How to 'find' only text files?解除的

    【讨论】:

    • 优雅的解决方案!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 2020-12-16
    • 1970-01-01
    • 2015-10-18
    相关资源
    最近更新 更多