繁体   English   中英

Shell 脚本 UNIX

[英]Shell scripting UNIX

我们有一个包含几个元素列表的文件,必须检查每个元素是否存在于包含多个文件夹、子文件夹和文件的目录中。 如果我们找到特定元素,我们应该将其填充到一个文件中,如果它不存在,则必须填充到另一个文件中...我们如何使用 unix shell 脚本来实现? 示例:file1: ABCD 如果我们在任何文件中找到元素 A/B/C/D,则应将其填充到名为“present.txt”的文件中,否则应填充到“Absent.txt”中。 提前致谢

这不是一个代码编写服务,但无事可做,我还是为你做了,但老实说,除非尝试自己编写,否则你不会学到很多东西。

您没有说明元素文件中的每行是否有一个文件名,或者每行有几个。 我的测试输入文件 gash.txt 具有以下内容:

A B C D
E F G H
I J K L

如果每行一个,那么脚本会更简单。 这里是:

#!/bin/sh

# Initialise filenames
elements=gash.txt
directory=gash
present=present.txt
absent=absent.txt

# Note that when these are used I enclose them in "quotes"
# This is to guard against embedded spaces in the names

# Zeroise files
> "$present"
> "$absent"

# If you have command-line arguments then save them here
# because I am about to blow them away with the 'set'

# 'read' reads each line into variable 'REPLY' by default
while read 
do
    # This 'set' trick will overwrite the program parameters
    # It will NOT work if the names in $elements have embedded whitespace
    set $REPLY

    # This loops through the command-line arguments by default
    for fname
    do 
        # if you don't know the 'find' command then look at 'man find'
        # Note that 'find' returns 0 even if it didn't find the file
        result=$(find "$directory" -name "$fname")

        # The '-n' test returns true if $result is not empty
        if [[ -n $result ]]
        then
            echo "$fname found"
            echo "$fname" >> "$present"
        else
            echo "$fname not found"
            echo "$fname" >> "$absent"
        fi

    done

done < "$elements"

一个更复杂的版本会从文件名构建一个模式,并只使用一次“查找”调用来进行搜索,但生命太短暂了(也许是以后的好项目)。

随意问的问题!

你也可以这样做:

文件 1 包含:

A
B
C
D

代码 :

directory="your path"

cat file1 | while read line
do
     res=$(find $directory -name "$line")
     if [[ -n $res ]]
     then
         echo $line >> present.txt
     else
         echo $line >> absent.txt
     fi
done

此致

暂无
暂无

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

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