In this article we're going to quickly demonstrate how to concatenate specific lines of a file using AWK's built-in ORS and NR
AWK's ORS will print the output with the specified delimiter. AWK's NR built in gives you the total line numbers or records being processed. We're going to put them together to create some output magic.
First, let's create a text file to work from. Open up your terminal, go to your desired file directory create a file
Open the file with vim and press i to switch to insert mode.
vim lines.txt i
Next, add this content to the file:
Jill 98 97 90 A Billy 85 78 93 B Ted 70 68 82 C Claire 68 67 70 D
Press esc key to exit insert mode and :wq to save and exit the file. Now we're ready to use AWK. Let's right our command then break it down.
awk 'ORS=NR%2?",":"\n"' ./lines.txt
First, we start the command with `awk`. Next, we're going to use AWK's built-in ternary function ( if else written like '?:') to check if the output is an odd or even line number (ORS=NR%2), separate each with a comma if it's odd or add a line break it's even. AWK's ORS variable sets an output delimiter, in this case the result of NR%2. AWK's NR gives either the line number or total number of records. In this case we use it for line numbers. AWK will concatenate every two lines using the modulo operator to check if the line number has a remainder when divided by 2. If there is a remainder of 1 (odd line number, so true), then a comma will be appended... if not (even line number, so false) then a line break will be appended.
The output resulting output should look like this:
Jill 98 97 90,A Billy 85 78 93,B Ted 70 68 82,C Claire 68 67 70,D