LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Creating Tab Spacing Between Two Values in AWK Command (https://www.linuxquestions.org/questions/linux-newbie-8/creating-tab-spacing-between-two-values-in-awk-command-4175708597/)

klmcguire 02-25-2022 04:00 PM

Creating Tab Spacing Between Two Values in AWK Command
 
First, if there is a specific way to insert code in these questions, let me
know. Sorry if I did it wrong on my first post.

I am trying to format spacing in my awk command shell script. In the for loop below, I am pulling two values from two specific columns and a specific row number, from a separate file. All of that works, I just need to create tab spacing between the two values, $3 and $4. How is this done?

for ((i=$START;i<=$END;i++))
do
awk -v i="$i" 'FNR == 46 {print "Complex "i" "$3" "$4" \n\n"}' mmpbsa_ab$i.log >> MMPBSA-Energies.dat
sleep 3;
done

boughtonp 02-25-2022 04:34 PM

Quote:

Originally Posted by klmcguire (Post 6333220)
First, if there is a specific way to insert code in these questions, let me
know.

It's "[code]..[/code]" - see https://www.linuxquestions.org/quest....php?do=bbcode


Quote:

I just need to create tab spacing between the two values, $3 and $4. How is this done?
"\t" is the escape for tab character, so simply "print $3"\t"$4" will do that.

Alternatively, if you want it between all fields, you could set Awk's output field separator (OFS) variable instead, e.g:
Code:

$ echo 'a b' | awk 'BEGIN{OFS="\t"} {print "prefix",$1,$2,"suffix"}' | cat -A
prefix^Ia^Ib^Isuffix$

(Where "cat -A" renders tabs as "^I")


klmcguire 02-25-2022 04:42 PM

Awesome! The first example works great. Out of curiosity, instead of a tab space, can you define any amount of space, say 2 or 3 or even 10, etc?

Turbocapitalist 02-26-2022 03:57 AM

You can set OFS to any value you see fit, see "man awk" for the details, but it would be the same between each of the fields printed out when printed as a whole line.

There are different versions of AWK so you will need to check, but most or all of them have a printf() function. That works like any other printf() and you can use it to provide leading or trailing spaces to pad out a field or fields. But then you'd have to enumerate the fields printed.


All times are GMT -5. The time now is 07:27 AM.