简体   繁体   English

UNIX-自动确定字段分隔符和记录(EOL)分隔符?

[英]unix - automatically determine field separator and record (EOL) separator?

Say you have 20 files and you don't won't to look at each one but instead have a script determine the format of the file. 假设您有20个文件,而您不会看每个文件,而是有一个脚本来确定文件的格式。

ie bash findFileFormat direcName 即bash findFileFormat direcName

Then loops through each file in a directory and print out the filename plus whether it has a delimiter (in which case is it a comma, pipe or otherwise) or fixed with for field separator and then what is the record separator. 然后循环遍历目录中的每个文件,并打印出文件名以及是否有定界符(在这种情况下,它是逗号,管道还是其他符号)或用for字段分隔符固定,然后是记录分隔符固定。 ie CR, LF, Ctrl+Z character.etc 即CR,LF,Ctrl + Z字符等

I was thinking because some files may have a lot of pipes and commas in the data, that it could use a count of each character per line to determine what the delimiter is --> if this process does not produce consistent numbers of the character per line it is safe to assume that the file uses a fixed width field separator. 我当时在想,因为某些文件的数据中可能包含很多竖线和逗号,所以它可以使用每行每个字符的计数来确定分隔符是什么->如果此过程不能在每个字符中产生一致的字符数可以肯定地说,该文件使用了固定宽度的字段分隔符。

Is there a command or script that can be used to determine these 2 bits of info for each file? 是否有命令或脚本可用于确定每个文件的这两位信息?

Here's a small python script that will do as a starting point for what you need: 这是一个小的python脚本,它将作为您所需的起点:

import sys

separators = [',', '|']
file_name = sys.argv[1]

def sep_cnt(line):
  return {sep:line.count(sep) for sep in separators}

with open(file_name, 'r') as inf:
  lines = inf.readlines()

cnts = [sep_cnt(line) for line in lines]
print(cnts)

def cnts_red(a, b):
  c = {}
  for k, v in a.iteritems():
    if v > 0 and v == b[k]:
      c[k] = v
  return c

final = reduce(cnts_red, cnts[1:], cnts[0])

if len(final) == 0:
  ftype = 'fixed'
else:
  ftype = 'sep by ' + str(final.iteritems().next()[0])

print(ftype)

Name the above heur_sep.py and run this somewhere safe (eg /tmp): 命名上面的heur_sep.py并在安全的地方运行它(例如/ tmp):

# Prepare
rm *.txt

# Commas
cat >f1.txt <<e
a,a,a,a
b,b,b,b
c,c,c,c
e

# Pipes
cat >f2.txt <<e
a|a|a|a
b|b|b|b
c|c|c|c
e

# Fixed width
cat >f3.txt <<e
1  2  3
1  2  3
1  2  3
e

# Fixed width with commas
cat >f4.txt <<e
1, 2  3
1  2, 3
1  2, 3,
e

for i in *.txt; do
  echo --- $i
  python heur_sep.py $i
done

You would have to do some more work to make this resistant to different kinds of errors, but should be a good starting point. 您将需要做更多的工作才能使它能够抵抗各种错误,但这应该是一个很好的起点。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM