1

My file has 4 numeric columns. Below testing if columns are identified correctly. tail -n +2 is to remove header.

tail -n +2 file.txt | awk '{print $1,$2,$3,$4}' | head

41261311 41261568 2798880 2799128
-115939711 -115940021 2799541 2799827
-115939159 -115939706 2800137 2800685
-115939033 -115939106 2801113 2801186
-115938419 -115938978 2801191 2801726
-115937404 -115937535 2812511 2812642
-115937075 -115937323 2813756 2814011
-115910025 -115910146 2818095 2818198
-115909932 -115909986 2818205 2818262
-115909723 -115909789 2818703 2818768

I want to add a 5th column which is col4 minus col3.

tail -n +2 file.txt | awk '{print $1,$2,$3,$4,$4-$3}' | head

 2481311 41261568 2798880 2799128
 286939711 -115940021 2799541 2799827
 548939159 -115939706 2800137 2800685
 735939033 -115939106 2801113 2801186
 535938419 -115938978 2801191 2801726
 131937404 -115937535 2812511 2812642
 255937075 -115937323 2813756 2814011
 103910025 -115910146 2818095 2818198
 575909932 -115909986 2818205 2818262
 655909723 -115909789 2818703 2818768

It doesn't add the 5th column and instead does something weird to the first column.

marked as duplicate by andcoz, Jeff Schaller, Jesse_b, slm Aug 2 '18 at 16:49

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2

Your file is ending in (Windows) CR LF instead of (Unix) LF.
The CR character moves the line to the start and then the value of the new calculated column is being printed over the first column.

Either use dos2unix, or filter the file with tr -d '\r' or simply use this:

awk 'NR>2 { gsub(/\r/,""); print $1,$2,$3,$4,$4-$3 } NR>12{exit}' file

remove the last NR>12{exit} to process the whole file.

Not the answer you're looking for? Browse other questions tagged or ask your own question.