Bash脚本删除文本文件中的所有行,直到字符串

时间:2011-01-08 14:36:25

标签: bash shell unix scripting filter

我有一个包含很多单词的文件:

one
two
three
four
tree
house
cat
dog
etc

我希望删除所有单词,直到“house”以这种方式获取:

cat
dog
etc

4 个答案:

答案 0 :(得分:6)

sed -n '0,/^house$/d;p' input.txt

答案 1 :(得分:0)

awk '
    BEGIN                  { noprint = 1; cue = ARGV[1]; ARGV[1] = ""}
    (!noprint)             { print }
    (noprint && $0 == cue) { noprint = 0 }
' house textfile

答案 2 :(得分:0)

您可以使用Perl one-liner轻松完成此操作,您当然可以将其合并到bash脚本中。

$ perl -ne 'print if $ok; $ok=1 if /^house$/' sample.txt 
cat
dog
etc

答案 3 :(得分:0)

您也可以使用Unix文本编辑器来执行此类任务。请注意,ed会将整个文件读入内存并在原位编辑文件,而无需先前的备份。

# prints result to stdout
printf '%s\n' H ',g/^house$/1,/^house$/d' ',p' | ed -s file
printf '%s\n' H ',g/^house$/1,//d' ',p' | ed -s file  # short version

# edits file in-place
printf '%s\n' H ',g/^house$/1,/^house$/d' wq | ed -s file

有关ed的更多信息,请参阅:

“使用脚本中的ed文本编辑器编辑文件”,

http://wiki.bash-hackers.org/howto/edit-ed

相关问题