【问题标题】:or operator and check for 6 null character and empty file (shell script)或运算符并检查 6 个空字符和空文件(shell 脚本)
【发布时间】:2012-12-13 03:19:28
【问题描述】:

下面的shell脚本是test.sh,目前它可以检查第10到15个字符是否等于'000000'。但是,它还应该检查 ' ' 6 个空空格以及空文件。问题是: 1) 如何检查空文件?

filename=$1

extracted=`head -1 $filename | cut -c10-15`

if [ $extracted -eq '000000' ] ###how to check for '      ' 6 null character with or operator?
then 
mv $filename new.$filename
fi

例如 输入文件:

案例1(6个0000000前后的一些字符)truefile.txt:

123456789000000161718

案例2(空文件)trueemptyfile.txt:

"there's nothing in this file. Empty. "

案例3(''前后的一些字符6个空字符)truepartialempty.txt

123456789      16171819

谢谢

还有一件事,所有这些文件都在 /temp 文件夹下

/temp> ls

 test.sh truefile.txt trueemptyfile.txt truepartialempty.txt

如何运行 test.sh 来检查所有文件。谢谢你。

是吗?

 sh test.sh *.*

【问题讨论】:

    标签: sh


    【解决方案1】:

    您必须更好地定义空字符的含义。

    当您显示' ' 时,这些是空格字符。 null 这个词有几种解释。在 DB 中,NULL 是一个特殊的词,意思是“一个未知的值”。在编程 NUL 或 NULL 或 null 时,可能意味着 char \000。该数字值用作特殊标记,以在“C”程序中(至少)指示“字符串结尾”。

    假设您的意思是空格字符,您可以准确地搜索它们是否已定义它们:

    if [ $extracted -eq '       ' ] 
    #--------------------^^^^^^^
    

    但当然要注意 $exacted 不能同时等于 000000 和 ' ',对吧?

    也许您会发现测试这些值会更容易,例如

    if echo "$extract" | grep -q '000000' ; then
          echo found 000000
    fi
    if echo "$extract" | grep -q '      ' ; then
           echo found spaces
    fi
    

    注意,由于 \000 对 c-lang 程序的特殊含义,包括 grep 和 unix 中的所有内容,你不能可靠地这样做

    if echo "$extract" | grep -q '\000\000\000\000\000\000\000' ; then 
     ....
    

    (实际上,这可能有效,因为“$extract”不是文件,但如果您尝试grep -q '\000' myFile,则可能无法可靠地工作,因为根据定义,内部带有 '\000' 的文件是二进制文件,而不是文本文件,而 grep 等是用于扫描文本文件的工具)。

    如果这确实是您想要的,可能有一些技巧可以找到这些,所以请编辑您的问题以表明这是否是您的要求。

    IHTH

    【讨论】:

    • 您好,谢谢。有没有办法检查空文件。 (需要检查多少个条件?)
    • test -s file 如果file 不为空,则返回true。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    • 1970-01-01
    • 2021-10-27
    • 2021-01-24
    • 2022-07-06
    • 2016-05-15
    相关资源
    最近更新 更多