【问题标题】:How to delete all lines containing more than three characters in the second column of a CSV file?如何删除 CSV 文件第二列中包含三个以上字符的所有行?
【发布时间】:2012-04-12 12:50:49
【问题描述】:

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

cave,ape,1
tree,monkey,2

第二行第二列的字符多于3个,所以会被删除。

【问题讨论】:

  • 是的,数据是 Unicode。它有来自各种语言的符号。
  • 您应该在您的要求中指定,因为这些实用程序中的大多数不支持 unicode(grep、sed....等)。他们只做单字节字符集。

标签: bash


【解决方案1】:

还没有人提供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

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

【讨论】:

  • 这可能适用于测试数据,但不适用于一般问题。也许sed -e '/^[^,]*,[^,]\{4\}/d' 可能会更防弹
【解决方案2】:
awk -F, 'length($2)<=3' input.txt

【讨论】:

  • 我对此进行了测试,它可以处理转义的逗号。 :)
【解决方案3】:

你可以使用这个命令:

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

grep 语法分解:

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

bash 的东西:

> 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 列在数据中包含逗号,则上述内容已简化,并且将不起作用。 (它不知道转义逗号和原始逗号之间的区别)

【讨论】:

  • +1,但如果第一个字段为空则无法正常工作。
【解决方案4】:

这是针对您的数据类型的过滤器脚本。它假设您的数据是 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    • 2011-09-05
    • 2017-10-01
    • 2012-10-01
    • 2020-07-02
    • 1970-01-01
    相关资源
    最近更新 更多