如何将所有以“foobar”开头的行移动到文件末尾?

时间:2011-11-03 20:57:15

标签: string bash

假设我有一个包含许多以foobar

开头的行的脚本

我想在保持订单的同时将所有行移到文档的末尾

e.g。从:

# There's a Polar Bear
# In our Frigidaire--
foobar['brangelina'] <- 2
# He likes it 'cause it's cold in there.
# With his seat in the meat
foobar['billybob'] <- 1
# And his face in the fish

# There's a Polar Bear
# In our Frigidaire--
# He likes it 'cause it's cold in there.
# With his seat in the meat
# And his face in the fish
foobar['brangelina'] <- 2
foobar['billybob'] <- 1

据我所知:

grep foobar file.txt > newfile.txt
sed -i 's/foobar//g' foo.txt
cat newfile.txt > foo.txt

5 个答案:

答案 0 :(得分:3)

这可能有效:

sed '/^foobar/{H;$!d;s/.*//};$G;s/\n*//' input_file

编辑:修改了foobar位于最后一行的角落

答案 1 :(得分:2)

grep -v ^foobar file.txt > file1.txt
grep ^foobar file.txt > file2.txt
cat file2.txt >> file1.txt

答案 2 :(得分:2)

这样做:

grep -v ^foobar file.txt > tmp1.txt
grep ^foobar file.txt > tmp2.txt
cat tmp1.txt tmp2.txt > newfile.txt
rm tmp1.txt tmp2.txt

-v选项会返回匹配给定模式的所有行。 ^标记了一行的开头,因此^foobar匹配以 foobar开头的行。

答案 3 :(得分:2)

grep -v ^foobar file.txt >newfile.txt
grep ^foobar file.txt >>newfile.txt

不需要临时文件

答案 4 :(得分:1)

你也可以这样做:

vim file.txt -c 'g/^foobar/m$' -c 'wq'

-c开关表示跟随Ex命令,g命令对包含给定模式的所有行进行操作,操作在此m$,这意味着“移动到文件末尾“(它保留了秩序)。 wq我们“保存并退出vim”。

如果这太慢,你也可以阻止vim阅读vimrc:

vim -u NONE file.txt -c 'g/^foobar/m$' -c 'wq'