1

如何将文件中包含至少一个匹配短语的所有行移动到文件末尾?例如,文件:

Do you like to read books?
Yes, do you like to watch movies?
No, but the fish does.

如果搜索短语是“book”和“movie”,那么上面的前两行将移动到文件的末尾,例如:

No, but the fish does.
Do you like to read books?
Yes, do you like to watch movies?
4

3 回答 3

3

这是一种快速而肮脏的方法:

(grep -v -e movie -e book file; grep -e movie -e book file) >newfile
于 2012-09-14T02:14:03.837 回答
1

这是你要找的吗?

grep "match1|match2" input.txt > tmp1
grep -v "match1|match2" input.txt > tmp2
cat tmp2 tmp1 > output.txt
rm tmp1 tmp2

或者,正如凯文所指出的,不使用临时文件:

cat <(grep "match1|match2" input.txt) <(grep -v "match1|match2" input.txt) > output.txt
于 2012-09-14T02:14:55.287 回答
1

这是完整 bash 的另一种方式:

#!/bin/bash -
declare -a HEAD
declare -a BOTTOM

while read -r line
do
        case "$line" in
                *book*|*movie*)
                        BOTTOM[${#BOTTOM[*]}]="${line}";
                        ;;
                *)
                        HEAD[${#HEAD[*]}]="${line}";
                ;;
        esac    # --- end of case ---
done < "$1"

for i in "${HEAD[@]}" "${BOTTOM[@]}"; do echo $i; done
于 2012-09-14T11:51:48.683 回答