从文件底部开始搜索和追加

时间:2013-11-25 09:29:27

标签: linux bash sed terminal

我怎样才能从底部搜索文件并找到它命中的第一个字符串,然后追加?即:

#file.test

Include sumeStuff1
Include sumeStuff2
Include sumeStuff3
Include sumeStuff4
Include sumeStuff5
Include sumeStuff6
Include sumeStuff7
Include sumeStuff8
Include SED_ENTRY

我知道我能做到:

find -type f -name "file.test" | xargs sed -i "s/Include somestuff8/Include somestuff8\nInclude SED_ENTRY/g"

但问题是,我正在构建一个脚本,我不知道什么是EXACT行是最后一个包含行,所以我需要从底部搜索然后在最后一个包含后添加一行线。

3 个答案:

答案 0 :(得分:1)

试试这个单行:

awk 'NR==FNR{if(/^YOUR_PAT$/)n=NR;next}FNR==n{$0="SED_ENTRY"}7' file file

对于您的示例,它将是:

 awk 'NR==FNR{if(/^Include sumeStuff8$/)n=NR;next}FNR==n{$0="Include SED_ENTRY"}7' file file

答案 1 :(得分:0)

使用awk

$ tac a | awk 'BEGIN{p=1} /^Include/ && p==1 {print "Include SED_ENTRY"; print; p=0}1' | tac
Include sumeStuff1
Include sumeStuff2
Include sumeStuff3
Include sumeStuff4
Include sumeStuff5
Include sumeStuff6
Include sumeStuff7
Include sumeStuff8
Include sumeStuff8
Include SED_ENTRY

解释

  • tac以相反的方式打印文件。
  • awk 'BEGIN{p=1} /^Include/ && p==1 {print "Include SED_ENTRY"; print; p=0}1'"Include SED_ENTRY"开头的第一行之前添加"Include"并对其进行标记,以便不再打印该行。
  • tac最终撤消了输出。

答案 2 :(得分:0)

sed -n '1 h
$ {/^Include/ s/$/\
/ }
1! H
$ {x;s/\(.*Include [^[:cntrl:]]\{1,\}\)\(\n\)\(.*\)/\1\2Include SED_ENTRY\2\3/p;}' YourFile