awk

awk

Some helpful one-liners for awk

Add prefix and postfix to every line of a file:

awk '{print "PREFIX"$0"POSTFIX"}' FILE

 

Add the content of a variable to every 4-th row of a file

awk -v "n=4" -v i="$index" 'NR % n == 0 {$0 = i $0} {print}' tmp.fq > tmp.new

Explanation: first, we define variables with the -v option, the v represents the line number factor that we want to add the content of the variable and the i will take the content of the variable we have from some other bash command, here stored in $index. Then we divide the rows by our factor, if this goes without rest, it’s one of every fourth row, so we want to change it. Then we define the new line, first the index variable (in awk naming here i, and then added the old content, stored in $0. Finally we print it.

If we want further, not change every n-th line start counting from line one, but e.g. line 2,6,10,14, … we can also change the part NR % n to (NR +2) % n

Leave a Reply