3

如何删除 CSV 文件中第二列中包含超过 3 个字符的所有行?例如:

cave,ape,1
tree,monkey,2

第二行在第二列中包含超过 3 个字符,因此将其删除。

4

4 回答 4

9
awk -F, 'length($2)<=3' input.txt
于 2012-04-12T12:55:39.743 回答
2

你可以使用这个命令:

grep -vE "^[^,]+,[^,]{4,}," test.csv > filtered.csv

grep 语法的分解:

-v = remove lines matching
-E = extended regular expression syntax (also -P is perl syntax)

重击的东西:

> filename = overwrite/create a file and fill it with the standard out

正则表达式语法的细分:

"^[^,]+,[^,]{4,},"

^ = beginning of line
[^,] = anything except commas
[^,]+ = 1 or more of anything except commas
, = comma
[^,]{4,} = 4 or more of anything except commas

请注意,如果前 2 列在数据中包含逗号,则上述内容已简化并且不起作用。(它不知道转义逗号和原始逗号之间的区别)

于 2012-04-12T13:00:56.193 回答
2

还没有人给出sed答案,所以这里是:

sed -e '/^[^,]*,[^,]\{4\}/d' animal.csv

这是一些测试数据。

>animal.csv cat <<'.'      
cave,ape,0
,cat,1
,orangutan,2
large,wolf,3
,dog,4,happy
tree,monkey,5,sad
.

现在来测试:

sed -i'' -e '/^[^,]*,[^,]\{4\}/d' animal.csv
cat animal.csv

只有猿、猫和狗应该出现在输出中。

于 2012-04-12T14:15:05.157 回答
2

这是您的数据类型的过滤器脚本。它假设您的数据是 utf8

#!/bin/bash
function px {
 local a="$@"
 local i=0
 while [ $i -lt ${#a}  ]
  do
   printf \\x${a:$i:2}
   i=$(($i+2))
  done
}
(iconv -f UTF8 -t UTF16 | od -x |  cut -b 9- | xargs -n 1) |
if read utf16header
then
 px $utf16header
 cnt=0
 out=''
 st=0
 while read line
  do
   if [ "$st" -eq 1 ] ; then
     cnt=$(($cnt+1))
   fi
   if [ "$line" == "002c" ] ; then
     st=$(($st+1))
   fi
   if [ "$line" == "000a" ]
    then
     out=$out$line
     if [[ $cnt -le 3+1 ]] ; then
        px $out
     fi
     cnt=0
     out=''
     st=0
   else
    out=$out$line
   fi
  done
fi | iconv -f UTF16 -t UTF8
于 2012-04-13T00:08:22.417 回答