问题描述
我正在编写一个 shell 脚本,它接受一个命令行参数,一个文件路径(可能是相对的或绝对的).脚本应检查该文件并打印一行包含以下短语的行:
I am working on a shell script that takes a single command line parameter, a file path (might be relative or absolute). The script should examine that file and print a single line consisting of the phrase:
Windows ASCII
Windows ASCII
如果文件是带有 CR/LF 行终止符的 ASCII 文本文件,或者
if the files is an ASCII text file with CR/LF line terminators, or
别的东西
如果文件是二进制或带有Unix"LF 行终止符的 ASCII.
if the file is binary or ASCII with "Unix" LF line terminators.
目前我有以下代码.
#!/bin/sh
file=$1
if grep -q "\r\n" $file;then
echo Windows ASCII
else
echo Something else
fi
它正确显示信息,但是当我通过诸如/bin/cat 之类的不是 Windows ASCII 类型的内容时,它仍然将其标识为 Windows ASCII.当我传递 .txt 文件类型时,它会按预期显示其他内容,它只是在显示 Windows ASCII 的文件夹上.我想我没有正确处理它,但我不确定.有关如何解决此问题的任何指示?
It displays information properly, but when I pass something that is not of Windows ASCII type through such as /bin/cat it still id's it as Windows ASCII. When I pass a .txt file type it displays something else as expected it is just on folders that it displays Windows ASCII. I think I am not handling it properly, but I am unsure. Any pointers of how to fix this issue?
推荐答案
当你指定你只需要区分两种情况时,这应该有效.
As you specify you only need to differentiate between 2 cases, this should work.
#!/bin/sh
file="$1"
case $(file "$file") in
*"ASCII text, with CRLF line terminators" )
echo "Windows ASCII"
;;
* )
echo "Something else"
;;
esac
正如您指定的#!/bin/sh
,或者如果您的目标是完全向后兼容,您可能需要更改
As you have specified #!/bin/sh
, OR if your goal is total backward compatibility, you may need to change
$(file "$file")
与
`file "$file"`
要使用包含空格的文件名的脚本,请注意所有 $
变量名称现在都用双引号括起来.并且您还必须在调用脚本时引用文件名中的空格字符,即
To use your script with filenames that include spaces, note that all $
variable names are now surrounded with double-quotes. AND you'll also have to quote the space char in the filename when you call the script, i.e.
myFileTester.sh "file w space.txt"
OR
myFileTester.sh 'file w space.txt'
OR
myFileTester.sh file\ w\ space.txt
OR
此外,如果您必须开始区分 file
可以分析的所有可能的情况,那么您将拥有一个相当大的 case 语句.AND file
因其返回的不同消息而臭名昭著,这取决于 /etc/file/magic
的内容、操作系统、版本等.
Also, if you have to start discriminating all the possible cases that file
can analyze, you'll have a rather large case statement on your hands. AND file
is notorious for the different messages it returns, depending on the the contents of /etc/file/magic
, OS, versions, etc.
IHTH
这篇关于查找文件类型的shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!