5

I am manipulating data from a text file with the following data structure:

"1111","2222","3333","4444","5555","6666","7777","2017/12/15 16:26:00"

I am trying to change the '/' in the date to '-'. Here is my awk command:

awk -F "," '{gsub("/", "-", $8); print}' my-input.txt

It successfully changes the /, but has the unintended consequence of replacing the ',' commas with a ' ' space character:

"1111" "2222" "3333" "4444" "5555" "6666" "7777" "2017-12-15 16:26:00"

Does anyone know why this is happening?

3
  • 4
    awk -F "," 'BEGIN {OFS = ",";} {gsub("/", "-", $8); print}' my-input.txt or awk -F "," -v OFS="," '{gsub("/", "-", $8); print}' my-input.txt – taliezin Mar 1 '18 at 9:13
  • 3
    Right, if you define your input file separator to be ,, and you want to keep it, then you have to define your output file separator as well. – pfnuesel Mar 1 '18 at 9:16
  • Thank you, I overlooked defining the output file separator. – GustavMahler Mar 1 '18 at 9:23
13

As pointed out by taliezin and pfnuesel, when defining the input file separator as a ',' it is necessary to also define the output file separator as a ',' to keep it. If the output file separator is omitted and a modification to an existing field has been done, awk will use the default value, in this case a ' ' [space] character.

The below is the corrected awk command:

awk -F "," -v OFS="," '{gsub("/", "-", $8); print}' my-input.txt

Which outputs the intended result which maintains the ',':

"1111","2222","3333","4444","5555","6666","7777","2017-12-15 16:26:00"
2
  • 4
    To be more specific: The output file separator needs to be defined if awk is provoked to re-form its fields. This happens when you modify a field. If no modification to existing fields is done, the separator will be kept. – Kusalananda Mar 1 '18 at 9:56
  • Thanks for the input Kusalananda. I've updated my answer. – GustavMahler Mar 1 '18 at 10:44
1

Since the requirement is to "change the '/' in the date to '-'", which is a simple character substitution, why not use sed? sed 's///-/g' my-input.txt

1
  • 2
    Because I know how to target a single field using awk ($8), whereas I don't know how to achieve that using sed. By targeting a single field (column), it eliminates unwanted global substitutions occurring. – GustavMahler Mar 1 '18 at 18:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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