[英]In Shell, how can I make an array of files and how do I use it to then compare it to another file?
How do I make an array of files in shell. 如何在Shell中制作文件数组。 Is it just 只是
files = (file1.txt file2.txt file3.txt)
or is it 还是
files = ("file1.txt" "file2.txt" "file3.txt)
If later on in the program I want to refer to this array and pick a specific file to read, how would I do that. 如果稍后要在程序中引用该数组并选择要读取的特定文件,我将如何处理。 I am asking because I would like to have a conditional that would read that file and compare it to an output file. 我问是因为我想有一个条件,可以读取该文件并将其与输出文件进行比较。
Would I just do: ( I know I can't do this) 我会做:(我知道我做不到)
if grep -q ${outputs[i]} output; then
#etc.
But what should I do instead then? 但是我该怎么办呢?
No spaces around =
in assignments, arrays are no excepetion. 在赋值中, =
周围没有空格,数组也不例外。
files=( file1.txt "file2.txt" )
Quotes around file names are needed if file names contain special characters, eg whitespace, parentheses, etc. 如果文件名包含特殊字符,例如空格,括号等,则需要在文件名前后加上引号。
You can use a for
loop to walk the array: 您可以使用for
循环遍历数组:
for file in "${array[@]}" ; do
if grep -q "$file" output ; then
Are you sure you want to use $file as the regular expression? 您确定要使用$ file作为正则表达式吗? Then you need to handle regex characters specially, ie dot, caret, dollar sign, etc. 然后,您需要专门处理正则表达式字符,例如点,插入号,美元符号等。
If you want to compare contents of the two files, use diff
, not grep
. 如果要比较两个文件的内容,请使用diff
而不是grep
。
if diff -q "$file" output > /dev/null ; then
echo Same
else
echo Different
fi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.