Replace line after match

Given this file

$ cat foo.txt
AAA
111
BBB
222
CCC
333

I would like to replace the first line after BBB with 999. I came up with this command

awk '/BBB/ {f=1; print; next} f {$1=999; f=0} 1' foo.txt

but I am curious to any shorter commands with either awk or sed.

Answers


This might work for you (GNU sed)

sed '/BBB/!b;n;c999' file

This is some shorter:

awk 'f{$0="999";f=0}/BBB/{f=1}1' file

f {$0="999";f=0} if f is true, set line to 999 and f to 0 /BBB/ {f=1} if pattern match set f to 1 1 print all lines, since 1 is always true.


awk '/BBB/{print;getline;$0="999"}1' your_file

$ awk '{print (f?999:$0); f=0} /BBB/{f=1}' file    
AAA
111
BBB
999
CCC
333

can use sed also, it's shorter

sed '/BBB/{n;s/.*/999/}'

sed 's/\(BBB\)/\1\
999/'

works on mac


Need Your Help

Change sprintf into simple UNION

php mysql

$STH_1 = $DBH_R->query("SELECT table_name

Table variable in a stored procedure

sql sql-server tsql stored-procedures

I would like to create a simple stored procedure which take as a parameter existing tables.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.