I wrote an awk script designed to inject a function in certain definition files. It looks for lines containing a two word phrase, when found it adds a paragraph after that line, in which the second parameter is used at one point. In this example: If file.txt contains the words "foo bar" on a line, we want to add after it the lines "{" followed by "func(bar)" followed by "}", awk should see $1 as "foo" (static identifier) and $2 as "bar" (can be anything so we read it):
awk '{
print $0
if($1 == "foo" && $2 != "") {
print "{"
print "func(" $2 ")"
print "}"
}
}' file.txt > file_new.txt
The issue is that $2 gains an unwanted newline at the end. This particularly seems to happen if there's nothing else on the line after it. Therefore the result in the produced file ends up being this:
foo bar
{
func(bar
)
}
Instead of the correct format:
foo bar
{
func(bar)
}
Everything else works fine, only problem is this newline getting stored in the second parameter for a strange reason. What do you suggest to get rid of it?
Regarding separators: It's worth noting the detected line can contain any mixture of spaces and tabs, either before after or between the two words. This means something like " foo bar "
should still ensure $1 is foo and $2 is bar.
Edit: With the provided example below, the file.txt would be something among the following lines. For different tests try adding spaces or tabs before / between / after foo and bar, as well as the empty line under it:
abc xyz
foo bar
123 789
This is the output of grep foo file.txt | od -c
on the original file I'm getting an issue with, it's larger and contains different words but is the exact same functionality as simplified here:
0000000 \t s p e c u l a r m a p \t
0000020 t e x t u r e s / d a r k m o
0000040 d / m e t a l / f l a t / g e n
0000060 _ s m o o t h _ g o l d 0 1 _ s
0000100 _ t i l i n g _ 1 d \n s
0000120 p e c u l a r m a p \t t
0000140 e x t u r e s / d a r k m o d /
0000160 m e t a l / f l a t / g e n _ s
0000200 m o o t h _ g o l d 0 1 _ s _ t
0000220 i l i n g _ 2 d \n
0000231