3

I am running the following awk command to project the 1st and 15th columns from an input file to an output . The problem start when the output file is written with a space delimeter

     awk -F "|" '{print $1,$15}' 1st_rm_text_from_transactions_22_7_14.plt > manual_memos_text_from_transactions_22_7_14.plt

How do I control the deilmeter (I need | ) in the output file ?

thanks

user3628777
  • 529
  • 3
  • 10
  • 20

3 Answers3

3

You control it with the output separator variable OFS

awk -F "|" '{OFS="|"; print $1,$15}' 1st_rm_text_from_transactions_22_7_14.plt > manual_memos_text_from_transactions_22_7_14.plt

A better way would be to add a begin section in order to avoid setting the variable every line (as suggested in the other answers and comments):

awk -F "|" 'BEGIN {OFS="|"} {print $1,$15}' 1st_rm_text_from_transactions_22_7_14.plt > manual_memos_text_from_transactions_22_7_14.plt

See here

Community
  • 1
  • 1
martin
  • 3,149
  • 1
  • 24
  • 35
  • 1
    Good. In this case you can also use `BEGIN{FS=OFS="|"}`. – fedorqui Jul 29 '14 at 11:13
  • Now that I see, you are setting `OFS` every single line. This is not very optimal... It should be within the `BEGIN{}` block, as I said before, or as a parameter (the way Kent suggests). – fedorqui Jul 29 '14 at 13:31
  • Yes, I know, I wanted a simple solution without too many additions. I'll modify my answer to add the begin section. – martin Jul 29 '14 at 13:53
  • 1
    For the record: On a file with 40k lines, there was virtually no difference between the two. – martin Jul 29 '14 at 14:00
  • Interesting! I would have said that it would significantly slow down the performance. Good one. – fedorqui Jul 29 '14 at 14:20
3
awk -F "|" -v OFS="|" '...code..'

or

awk 'BEGIN{FS=OFS="|"}{code...}'
Kent
  • 189,393
  • 32
  • 233
  • 301
1

Simply use FS instead of comma in the print statement.

awk -F"|" '{print $1FS$15}' infile > outfile
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274