TSV 파일에서 열이 비어 있거나 모두 비어 있는 행을 제거하는 방법은 무엇입니까?

TSV 파일에서 열이 비어 있거나 모두 비어 있는 행을 제거하는 방법은 무엇입니까?

다음과 같이 탭으로 구분된 파일이 있습니다 myfile.tsv.

abc\tfoo
xyz\tbar

하지만 때로는 다음과 같은 빈 열이 있는 경우도 있습니다.

abc\tfoo
xyz\tbar
what\t
\tthe
bleep\tsleep

$ printf "abc\tfoo\n" > myfile.tsv
printf "xyz\tbar\n" >> myfile.tsv
printf "what\t\n" >> myfile.tsv
printf "\tthe\n" >> myfile.tsv
printf "bleep\tsleep\n" >> myfile.tsv

$ cat myfile.tsv 
abc foo
xyz bar
what    
    the
bleep   sleep

다음과 같이 빈 열이 있는 행을 삭제하는 Python 스크립트를 작성할 수 있습니다.

with open('myfile.tsv') as fin:
    for line in fin:
        x, y = line.strip().split('\t')
        x = x.strip()
        y = y.strip()
        if x and y:
            print(line)
            

하지만grep, sed또는 awk다른 명령 과 같은 일부 Unix 쉘 명령으로 동일한 작업을 수행하려면 어떻게 해야 합니까 ?


나는 또한 비슷한 것을 시도했습니다 grep.

grep -e ".\t." myfile.tsv 

이것은 작동하는 것처럼 보이지만 열에 공백이 있는 경우에는 작동하지 않습니다.

$ printf "abc\tfoo\n" > myfile.tsv
printf "xyz\tbar\n" >> myfile.tsv
printf "what\t  \n" >> myfile.tsv
printf "  \tthe\n" >> myfile.tsv
printf "bleep\tsleep\n" >> myfile.tsv

$ grep -e ".\t." myfile.tsv       
abc foo
xyz bar
what      
    the
bleep   sleep

답변1

밀러( ) 사용 mlr:

$ cat -t myfile.tsv
abc^Ifoo
xyz^Ibar
^I
what^I
^Ithe
bleep^Isleep
$ mlr --tsv filter 'bool empty=false ; for (k,v in $*) { empty = is_empty(v); empty { break }  } !empty' myfile.tsv
abc     foo
xyz     bar
bleep   sleep

다음의 해당 콘텐츠 awk:

$ awk -F '\t' '{ empty = 1; for (i = 1; i <= NF; ++i) if (empty = (length($i) == 0)) break }; !empty' myfile.tsv
abc     foo
xyz     bar
bleep   sleep

답변2

사용sed

$ sed -E '/^\t|\t$/d' myfile.tsv
abc     foo
xyz     bar
bleep   sleep

답변3

행의 모든 ​​필드에 공백, 탭만 포함되어 있거나 비어 있는 행을 제거하려면 다음을 포함하는 행을 일치시키고 제외하면 됩니다.공백만:

grep -v '^[[:space:]]*$'

관련 정보