本文介绍了如果在文件中找到数字ID,则Bash循环以建立目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用awk在目录中创建子目录(该目录始终是file1的最后一行,每个块用空行分隔),如果第2行中的数字始终在file1$2中找到file2格式的xx-xxxx)的前6位数字.

I'm trying to use awk to create sub-directories in a directory (which is always the last line of file1, each block separated by an empty line), if the number in line 2 (always the first 6 digits in the format xx-xxxx) of file2 is found in $2 of file1.

已经在/path/to/directory中创建了目录.在下面的示例中,/path/to/directory中已经存在Directory2_2,并且由于在file1$2中找到了19-000319-000419-0005,因此将它们移到了Directory2_2.

The directory will already be created in /path/to/directory. In the example below, Directory2_2 already exists in /path/to/directory and since 19-0003, 19-0004 and 19-0005 are found in $2 of file1, they are moved to Directory2_2.

文件1

xxxx_006 19-0000_Lname-yyyy-zzzzz
xxxx_007 19-0001_Lname-yyyy-zzzzz
Directory1_1

xxxx_008 19-0003_Lname-yyyy-zzzzz
xxxx_009 19-0004_Lname-yyyy-zzzzz
xxxx_020 19-0005_Lname-yyyy-zzzzz
Directory2_2

文件2

xxxx
19-0003-xxx-xxx-xxx_000-111
yyyy
xxxx
19-0004-xxx-xxx-xxx_000-111
yyyy
xxxx
19-0005-xxx-xxx-xxx_000-111
yyyy

在bash中寻求循环

for f in $(awk { print cut -d'_' -f1 }' file2); do
    [[ "$f" == $2 ]] && mkdir -p "$f" /path/to/directory
done

所需的输出

Directory2_2
 19-0003-xxx-xxx-xxx_000-111
 19-0004-xxx-xxx-xxx_000-111
 19-0005-xxx-xxx-xxx_000-111

推荐答案

如果目录名不包含空格(在以段模式处理的file1和以行模式处理的file2以下):

If the directory names don't contain spaces (below file1 processed in paragraph-mode and file2 in line-mode.):

awk 'NR==FNR { for(i=2; i<NF; i+=2) a[substr($i,1,7)] = $NF; next }
     { k = substr($0, 1, 7) }
     k in a { cmd = sprintf("mkdir -p %s/%s", a[k], $0); print(cmd); }
' RS= file1 RS='\n' file2
#mkdir -p Directory2_2/19-0003-xxx-xxx-xxx_000-111
#mkdir -p Directory2_2/19-0004-xxx-xxx-xxx_000-111
#mkdir -p Directory2_2/19-0005-xxx-xxx-xxx_000-111

print(cmd)更改为 system(cmd)以实际运行命令.

change print(cmd) to system(cmd) to actually run the command.

注意:如果目录名称包含空格,则可能需要设置IFS ='\ n'才能将$ NF用作file1中的基本目录:

Note: if the directory names contain spaces, you might need to setup IFS='\n' in order to use $NF for the base directory in file1:

awk 'NR==FNR { for(i=1; i<NF; i++) a[substr($i,index($i," ")+1,7)] = $NF; next }
     { k = substr($0, 1, 7) }
     k in a { cmd = sprintf("mkdir -p \"%s\"/\"%s\"", a[k], $0); print(cmd); }
' FS='\n' RS= file1 RS='\n' file2

这篇关于如果在文件中找到数字ID,则Bash循环以建立目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 04:04