Reputation: 54
Currently working on Solaris
I need to search for a specific string in a text file and, if found, join it to the previous line. For example:
if logical condition
then
i = i + 1
Would become
if logical condition then
i = i + 1.
I'm sure I can do this with awk using a hold space of some sort but my awk skills are a little rusty.
Addendum: Apologies, I should have been more specific. The match is triggered by the appearance of the string "then". I have no knowledge of the contents of the previous line - it could be anything. Whatever it is I need to concatenate the "then" to it.
Upvotes: 0
Views: 56
Reputation: 1118
Try this:
awk '
function dump(trailing_line) {
for (i = 0; i < length(previous) - 1; i++)
print previous[i]
if (trailing_line) {
print previous[i] trailing_line
} else {
print previous[i]
}
i = 0
delete previous
}
/then/ {
dump(" then")
next
}
{
previous[i++] = $0
}
END {
dump("")
}
' your_input_file
If you truly have no knowledge of what comes before the then
, you will have to store each line into an array and then dump them out before you emit the then
. Since you will also want to do this within the END
clause, it's easiest to make this "dumping" action into a function.
Upvotes: 0
Reputation: 203502
$ awk '{printf "%s%s", (NR>1?(/then/?FS:RS):""), $0} END{print ""}' file
if logical condition then
i = i + 1
Upvotes: 2