1

I have the following space delimited text file:

ra dec type
197.574288 -0.673779 coadd
201.236362 -1.007902 coadd
191.573312 5.039784 coadd

with "ra" "dec" and "type" as the headers for the file. I want to use an awk command to add a field with constant value "i" before the last field, and a field with constant value "pdr" after the last field so it looks like this:

ra dec i type pdr
197.574288 -0.673779 i coadd pdr
201.236362 -1.007902 i coadd pdr
191.573312 5.039784 i coadd pdr

So far, I've tried many different commands, such as

awk '{printf("i %s pdr2_wide\n",$3,$5)}' psffile.txt > psf50.txt
awk '{printf($1,$2,$3,"i %s pdr2_wide\n",$4,$5)}' psffile.txt > psf50.txt
awk -F '\ ' -v OFS='\ ' '{ $(NF-1) = i; print }' psffile.txt > psf50.txt <br />

EDIT: When I enter the command "awk '{ print $1,$2,"i",$3,"pdr" }' input" it gives me a weirdly formatted output:

ra dec i type pdr
197.574288 -0.673779 i coadd
 pdr
201.236362 -1.007902 i coadd
 pdr
191.573312 5.039784 i coadd
 pdr

Is there a way to fix this?

elo
  • 45
  • 4

2 Answers2

0
awk '{ print $1,$2,"i",$3,"pdr" }' input

output:

ra dec i type pdr
197.574288 -0.673779 i coadd pdr
201.236362 -1.007902 i coadd pdr
191.573312 5.039784 i coadd pdr
Luuk
  • 12,245
  • 5
  • 22
  • 33
  • Hi, thank you for your response. This command makes it so that the "pdr" of each line is beneath the "ra" number. I have edited my question so you can see this output file. I'm not sure why it is doing this. – elo Sep 27 '20 at 16:43
  • This must be because of different line-endings. Normally on unix (or linix) lines en with a CR (carriage return), on Windows lines end on CRLF (carriage return + line feed), and MacOS does somethin else... I was assuming CR as the end-of-line character. – Luuk Sep 27 '20 at 18:30
  • @Luuk: Unix/Linux/mac OS uses line feed (hex 0a) and Classic Mac OS uses only carriage return (hex 0d). – Cyrus Sep 27 '20 at 20:57
0
awk '{$NF= "i" FS $NF FS "pdr"}1' file

As you want to add fields near at the end, you could do this, for any fields numbers, also 1 at the end means print every line.

thanasisp
  • 5,855
  • 3
  • 14
  • 31
  • Thank you. This is giving me the same formatting problem as the suggestion above, where the "pdr" field is entered on a new line every line. I have edited my question to show what this output file looks like. – elo Sep 27 '20 at 16:48
  • Probably you have special characters, like \r or ^M at the end of the lines. Do you have any relationships with dos/windows? give a try to `dos2unix file > new_file` before the script. – thanasisp Sep 27 '20 at 16:59