找到一个固定宽度的文件的长度,稍微扭转一下



嗨,了不起的人/我的导师和所有善良的人。

我有一个固定宽度的文件,目前我正在试图找到那些包含x字节的行的长度。我尝试了几个awk命令,但它并没有给我想要的结果。我的固定宽度包含208字节,但很少有行不包含208字节。我正试图找出那些没有208字节的记录

这个cmd给了我文件长度

awk '{print length;exit}' file.text

在这里,我尝试打印包含101个字节的行,但没有成功。

awk '{print length==101}' file.text

这里的任何帮助/见解都将对非常有帮助

使用awk:

awk 'length() < 208' file

长度((给出的是字符的数量,而不是字节。此数字在unicode上下文中可能有所不同。您可以使用LANG环境变量强制awk使用字节:

LANG=C awk 'length() < 208' file

Perl来拯救!

perl -lne 'print "$.:", length if length != 208' -- file.text
  • -n逐行读取输入
  • -l在处理输入之前从输入中删除换行符,并将它们添加到print

对于长度不同于208的每一行,一行将打印行号($.(和行的长度。

如果您使用的是gawk,那么即使在典型的UTF-8语言环境模式下也没有问题:

length(s)         =  # chars native to locale, 
# typically that means # utf-8 chars
match(s, /$/) - 1 = # raw bytes   # this also work for pure-binary
# inputs, without triggering 
# any error messages in gawk Unicode mode

最佳示例:

0000000        3347498554      3381184647      3182945161       171608122
:   Ɔ  **   LJ  **   Ȉ  **   ɉ  **  㷽  **  **   : 210   :  n
072 306 206 307 207 310 210 311 211 343 267 275 072 210 072 012
:   ?  86   ?  87   ?  88   ?  89   ?   ?   ?   :  88   :  nl
58 198 134 199 135 200 136 201 137 227 183 189  58 136  58  10
3a  c6  86  c7  87  c8  88  c9  89  e3  b7  bd  3a  88  3a  0a
0000020
# gawk profile, created Sat Oct 29 20:32:49 2022
BEGIN {
1          __ = "306206307207310"  (_="210") 
"311211343267275"
1      print "",__,_
1      STDERR = "/dev/stderr"
1      print (             match(_,  /$/) - 1, "_" ) > STDERR  # *A
1      print ( length(__), match(__, /$/) - 1      ) > STDERR  # *B
1      print (     (__~_), match(__, (_) ".*")     ) > STDERR  # *C
1      print (     RSTART, RLENGTH                 ) > STDERR  # *D
}
1 | _   *A   # of bytes off "_" because it was defined as 0x88 210
5 | 11  *B   # of chars of "__", and 
# of bytes of it : 
#                   4 x 2-byte UC 
#                +  1 x 3-byte UC = 11
1 | 3   *C   # does byte 210 exist among larger string (true/1),
# and which unicode character is 1st to 
# contain 210 - the 3rd one, by original definition
3 | 3   *D   # notice I also added a ".*" to the tail of this match() :
# if the left-side string being tested is valid UTF-8,
# then this will match all the way to the end of string,
# inclusive, in which you can deduce :
#
#  "210 first appeared in 3rd-to-last utf-8 character"     

结合推断的理解:

RLENGTH    = "3 chars to the end, inclusive",

知道它左边有多少:

RSTART - 1 = "2 chars before",

产生3 + 2=5的总计数,确认length()的结果

相关内容

最新更新