2011-11-03 48 views
3

说我有一个行数开始foobar如何将'foobar'开头的所有行移动到文件末尾?

一个剧本,我想所有的线移动到文档的末尾,同时保持它们的顺序

例如从去:

# 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 
+2

提示:输出文件就是所有的行不foobar的开始,接着用foobar的开头的所有行。两个grep命令。 – Amnon

+0

@Amnon谢谢你指出。有道理,但我仍然不知道如何说bash – Abe

+0

@Amnon'-v'得到了它 – Abe

回答

3

这可能会实现:

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

编辑:修订的角落情况下foobar是最后一行

+0

差异显示它与其他两个相同,但一个班轮需要它(除非有更真棒的东西出现)。如果你能解释什么是“{H; d}; $ G; s/\ n /',那就太好了。 – Abe

+1

所有不包含字符串foobar的行都会直接通过。那些包含'foobar'的行被添加到一个名为保持空间的寄存器中,然后模式空间(当前行)被删除。在最后一行'$'保留空间(包含所有foobar行)被附加到模式空间,准备打印,但首先删除空行。 – potong

2
grep -v ^foobar file.txt > file1.txt 
grep ^foobar file.txt > file2.txt 
cat file2.txt >> file1.txt 
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

+0

为什么是克拉? –

+0

@David因为安倍希望从** foobar开始移动**行,而'^'标记行的开头。 – Bolo

+0

谢谢...和+1我已更新我的回答 –

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

不需要临时文件

+0

,这是行不通的,不仅因为你拼错grerp – Abe

+0

安倍:那么请告诉我为什么,因为它似乎在我的机器上工作正常 –

+0

你有两个不同的输出文件名。 – tripleee

1

您也可以这样做:

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

-c开关装置Ex命令下文中,g命令在含有给定的图案的所有行操作,并且这里的动作是m$这意味着“移动到文件结尾”(它保留了顺序)。 wq weans“保存并退出vim”。

如果速度太慢,还可以阻止VIM读取的vimrc:

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