I want to prepend and append a certain line of a file using awk.
Example:
Say i have a file with 5 lines, i want to awk the 3rd line and put "hello" at the beginning and "goodbye" at the end.
example file.
1. foo
2. foo
3. foo
4. foo
5. foo
output result hello 3. foo goodbye
and delete all other lines 1, 2, 4, 5,
Ive tried
awk 'NR==3 {print $0" goodbye"}' <file>
this appends the line with goodbye but i cannot figure out how to prepend the line with "hello"
Ive tried BEGIN and END in the command but unsure how to treat NR==3 ?
Desired output should be..
hello 3. foo goodbye
final output result hello 3. foo goodbye
and delete all other lines 1, 2, 4, 5,
Could you please try following. To print all lines only 3rd line with additional details.
awk 'FNR==3{print "hello " $0 " goodbye";next} 1' Input_file
OR
awk 'FNR==3{$0="hello " $0 " goodbye"} 1' Input_file
In case you want to print only 3rd edited line try:
awk 'FNR==3{print "hello " $0 " goodbye"}' Input_file
In case you want to print only 3rd line with use of BEGIN
and END
as per your attempt then try following.
awk 'BEGIN{ORS=" ";printf "hello "} FNR==3; END{printf("%s\n","goodbye")}' Input_file