如何检查文本文件在bash中是否具有制表符作为其分隔符? [英] How do you check if a text file had tab as its delimiter in bash?

查看:279
本文介绍了如何检查文本文件在bash中是否具有制表符作为其分隔符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个文本文件,它可能包含一个制表符作为其字段分隔符(定界符),或者可能有一个空格作为字段分隔符.我想检查该文本文件是否制成表格,否则我将对该文件进行其他操作.我正在使用bash脚本.因此,我对使用纯bash,sed,awk,grep等的任何东西都开放(注意:它们都是GNU).所以我在想这样的结构:

So I have a text file and it may have a tab as its field separator (delimiter) or it may have a space as a field separator. I would like to check if that text file is tabulated otherwise I will do something else with the file. I am using a bash script. So i'm open to anything with pure bash, sed, awk, grep, etc. (NOTE: that they are all GNU). So I am thinking of a structure like this:

if [if delimiter is tab]; then
    #do soemthing
elif [if delimiter is space]; then
    #do something else
fi

有什么建议吗?让我知道是否需要进一步的解释.谢谢!

Any suggestions? Let me know if further explanation is required. Thanks!

以下是更新的解释:文本文件的外观:

Here is an explanation update on what the text file looks like:

如果文本文件具有制表符作为定界符,则在每行上定界.如果文本文件有一个空格作为定界符,则不会在每一行都定界.

If the text file has a tab as delimiter, then it delimited on every line. If the text file has a space as delimiter, then it is NOT delimited every line.

以下是我可能会遇到的可能的文本文件的示例:

Here are examples of possible text files that I might be facing:

定界符为制表符:

col1   col2   col3
-------
1   2   3
4   5   6

分隔符为空格 :(空格介于12和3之间以及& 4和56之间)

Delimiter is space: (the space is between 12 and 3 && 4 and 56)

col1col2col3
-----------
12 3
4 56

推荐答案

假定只有在用制表符分隔文件时,制表符才会出现在第一行

Assuming a tab will only exist on the first line when the file is tab delimited then this

if awk '{exit !/\t/}' "$file"; then
    : # tab file
else
    : # space file
fi

应该做你想做的事.

也:

if [ -n "$(sed -n '/\t/p;q' "$file")" ]; then
    : # tab file
else
    : # space file
fi

这篇关于如何检查文本文件在bash中是否具有制表符作为其分隔符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆