如何在shell脚本中映射和比较文件名

时间:2017-03-28 13:53:22

标签: shell awk

我正在使用下面的代码来映​​射文件名

function insert_data()

{

            for file in `ls -lrt Added_to_* | awk '{print $9}'`
    do
            echo "Running for File: $file"
            map_file="mapping_rule_categories.txt"
          path=`ls -lrt Added_to_* | awk '{print $9}'`
                    output=`cat $map_file | awk -F "|" -vnick="$path" '{if("$8"=="$nick") print $9}'`
    echo $output
    done
}
insert_data;

其中 mapping_rule_categories.txt 的映射类似

Removed_from_drop.rules|Disabled_in_drop.rules | Disabled_and_modified_in_drop.rules | Modified_inactive_in_drop.rules|Modified_active_in_drop.rules | Enabled_and_modified_in_drop.rules | Enabled_in_drop.rules | Added_to_drop.rules | drop.rules

目录中的文件如下:

Added_to_botcc.rules
Added_to_compromised.rules
Added_to_drop.rules

我需要输出应该在使用map文件后打印文件名:

botcc.rules
compromised.rules
drop.rules

2 个答案:

答案 0 :(得分:1)

我真的不太了解你的问题(提示:做点什么)但是从输入到预期的输出:

将名称中带空格的文件添加到测试目录:

$ touch Added_to_this\ test  # advanced test with space in filename
$ ls                         # your files and then some
Added_to_botcc.rules        Added_to_drop.rules
Added_to_compromised.rules  Added_to_this test

处理文件:

$ for i in Added_to_* ; do echo ${i#Added_to_} ; done
botcc.rules
compromised.rules
drop.rules
this test

答案 1 :(得分:0)

@Shrawan - 您可以尝试以下解决方案 -

$cat filecomparision.sh 
function insert_data()
{
##### Looping on files in current directory to fetch only the filenames
 for file in $(ls -1rt Added_to_*) 
    do
          echo "Running for File: $file"
          map_file="mapping_rule_categories.txt"
          path=`ls -lrt Added_to_* | awk '{print $9}'`
          output=$(awk -F "|" -v nick="$file" '{gsub(/[[:space:]]/,""); if($8 ~ nick) print $9}' $map_file)
          echo "Output of file: $output"
    done
}
#######function Calling
insert_data
$ ./filecomparision.sh 
Running for File: Added_to_drop.rules
Output of file: drop.rules
Running for File: Added_to_compromised.rules
Output of file: 
Running for File: Added_to_botcc.rules
Output of file: