我在一个名为abc.txt srr.txt eek.txt abb.txt
等目录的目录中有数千个文件。我想只grep那些具有不同的最后两个字母的文件。例如:
良好的输出:abc.txt eek.txt
输出错误:ekk.txt dee.txt
。
这是我想要做的:
#!/bin/bash
ls -l directory |grep .txt
它会覆盖其中包含.txt
的每个文件。
如何grep具有两个不同姓氏的文件?
答案 0 :(得分:3)
我选择find
列出*.txt
个文件,然后grep
过滤掉最后两个字母相同的文件(使用反向引用):
find . -type f -name '*.txt' | grep -v '\(.\)\1\.txt$'
它实际上会拾取一个字符然后立即尝试在.txt
之前反向引用它,而-v
提供反向匹配,只留下不具有相同最后两个字符的文件。
更新:要移动找到的文件,您可以将mv
链接到命令:
find . -type f -name '*.txt' | grep -v '\(.\)\1\.txt$' | xargs -i -t mv {} DESTINATION
答案 1 :(得分:2)
解析ls
的结果不是一个好主意(请阅读此doc以了解原因)。以下是您在纯Bash中可以执行的操作,而不使用任何外部命令:
#!/bin/bash
shop -s nullglob # make sure glob yields nothing if there are no matches
for file in *.txt; do # grab all .txt files
[[ -f $file ]] || continue # skip if not a regular file
last6="${file: -6}" # get the last 6 characters of file name
[[ "${last6:1:1}" != "${last6:2:1}" ]] && printf '%s\n' "$file" # pick the files that match the criteria
# change printf to mv "$file" "$target_dir" above if you want to move the files
done
答案 2 :(得分:0)
我似乎通过使用它来实现我想要的目标:
ls -l |awk '{print $9}' | grep -vE "(.).?\1.?\."
awk '{print $9}'
仅打印.txt
个文件grep -vE '(.).?\1.?\.'
过滤了句点前三个字符不唯一的所有名称:aaa.txt
,aab.txt
,aba.txt
和baa.txt
都已过滤。< / LI>