Skip to content

Instantly share code, notes, and snippets.

@voyeg3r
Last active August 29, 2017 00:35
Show Gist options
  • Save voyeg3r/4fde0aeff533ad55bf91f02bb93945db to your computer and use it in GitHub Desktop.
Save voyeg3r/4fde0aeff533ad55bf91f02bb93945db to your computer and use it in GitHub Desktop.

awk ternary operator to insert blank line

seq 10 | awk 'ORS=NR%2 ? RS:RS RS'
seq 10 ........... gives us 1 to 10 (one by line)
| ................ pipes each line to awk

Awk uses a ternary operator like: statemente-condition ? if-true: if-false

If the result of Mod of NR equals to 1, it sets ORS to the RS (newline) if the result of Mod of NR equals to 0, it set ORS to RS RS (double newline) inserting hence a blank line

ORS .............. output register separator (default newline)
NR % 2  .......... Mod of the integer division of Number of Register (line number)

let's try something here:

echo '1%2' | bc 
1

echo '2%2' | bc
0

echo '3%2' | bc
1

Therefore:

seq 10 | awk 'ORS=NR % 2 ? RS:RS RS'

Portuguese explanation:

ORS ............ separador de registro de saída

Caso o módulo da divisão do Número do Registro NR por 2 for igual a 1 atribua uma quebra de linha para o separador de registro de saída, caso contrário atribua duas quebras de linha para o separador de registro de saída

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment