我有一个看起来像这样的文件:
ASDFGHJ|ASDFEW|ASFEWFEWAFEWASDFWE FEWFDWAEWA FEWDWDFEW|EWFEW|ASKOKJE
IOJIKNH|ASFDFEFW|ASKDFJEO JEWIOFJS IEWOFJEO SJFIEWOF WE|WEFEW|ASFEWAS
我遇到了这个文件的问题,因为它是用西里尔语编写的,数据库抱怨字节数(vs字符数)。我想检查,例如,第一个字段是否大于10个字节,第二个字段是否大于30个字节等。
我一直在尝试很多不同的东西:awc,wc ...我知道wc -c我可以计算字节但是我怎样才能只检索字段大于X的行?
有什么想法吗?
答案 0 :(得分:3)
如果您愿意使用perl
,那么这可能有所帮助。我添加了评论,以便您更轻松地遵循:
#!/usr/bin/perl
use strict;
use warnings;
use bytes;
## Change the file to path where your file is located
open my $data, '<', 'file';
## Define an array with acceptable sizes for each fields
my @size = qw( 10 30 ... );
LINE: while(<$data>) { ## Read one line at a time
chomp; ## Remove the newline from each line read
## Split the line on | and store each fields in an array
my @fields = split /\|/;
for ( 0 .. $#fields ) { ## Iterate over the array
## If the size is less than desired size move to next line
next LINE unless bytes::length($fields[$_]) > $size[$_];
}
## If all sizes matched print the line
print "$_\n";
}
答案 1 :(得分:3)
如果以字节为单位的字段比数组@m
中的相应成员长,则打印整行的Perl单行:
perl -F'\|' -Mbytes -lane '@m=(10,10,30,10); print if grep { bytes::length $_ > shift @m } @F' file
顾名思义,bytes::length
忽略编码并返回每个字段的长度(以字节为单位)。 -a
切换到Perl会启用自动拆分模式,从而创建包含所有字段的数组@F
。我已经使用管道|
作为分隔符(它需要使用反斜杠转义)。 -l
开关从行尾删除换行符,确保最终字段的长度正确。
-n
开关告诉Perl循环遍历文件中的每一行。 grep
在块中的条件上过滤数组@F
。我正在使用shift
删除并返回@m
的第一个元素,以便将@F
中的每个字段与@m
中的相应元素进行比较。如果筛选列表包含任何元素(即,如果任何字段长于其限制),则在此上下文中将评估为true。
答案 2 :(得分:1)
要获取特定FIELD
上某个LINE
的字节数,您可以发出以下awk
命令:
awk -F'|' -v LINE=1 -v FIELD=3 'NR==LINE{print $FIELD}' input.txt | wc -c
要打印每个字段的字节数,您可以使用一个小循环:
awk -F'|' '{for(i=1;i<NF;i++)print $i}' a.txt | \
while read field ; do
nb=$(wc -c <<<"$field")
echo "$field $nb"
# Check if the field is too long
if [ "$nb" -gt 40 ] ; then
echo "field $field is too long"
exit 1
fi
done