简体   繁体   English

bash(sed / awk?)在文件中查找行并在上面3行打印内容?

[英]bash (sed/awk?) find line in file and print stuff 3 lines above?

I want to find a line in a txt file and then insert string 3 lines above the found line 我想在txt文件中找到一行,然后在找到的行上方插入字符串3行

Input: 输入:

aaa
bbb
ccc
ddd
eee
fff

I want to look for "eee" and then print "WWW" 3 lines above it. 我要查找“ eee”,然后在其上方打印“ WWW” 3行。 Output: 输出:

aaa
WWW
bbb
ccc
ddd
eee
fff

I'm using awk and can only print "WWW" 1 line above "eee", and not 3: 我正在使用awk,并且只能在“ eee”上方打印“ WWW” 1行,而不能打印3:

awk '/eee/{print "WWW"} 4' file.txt

any ideas? 有任何想法吗?

单程:

awk '{a[NR]=$0;}/eee/{a[NR-3]="www\n" a[NR-3];}END{for(i=1;i<=NR;i++)print a[i];}' file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM