2012-09-14 17 views
1

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

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

如果搜索短语是“书”和“电影”,那么上面的前两条线将移动到文件末尾,如:

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

回答

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 
+1

可以跳过临时文件:'猫< (grep -v match)<(grep match)' – Kevin

3

这里有一个快速和肮脏的方式:

​​
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 
相关问题