Skip to content

Commit

Permalink
Implement -C for CSV output
Browse files Browse the repository at this point in the history
  • Loading branch information
ryuichiueda committed Nov 6, 2019
1 parent 38c9165 commit 5c2092c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
22 changes: 19 additions & 3 deletions opy
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import re
import codecs
from collections import defaultdict

__version__ = "2.2.1"
__version__ = "2.2.2"
__author__ = "Ryuichi Ueda"
__license__ = "MIT license"
__url__ = "https://github.com/ryuichiueda/opy"
Expand Down Expand Up @@ -225,7 +225,7 @@ def __dynamic_module_import(msg):
sys.exit(1)


def __print_list(rule, f, glo, loc):
def __print_list_normal(rule, f, glo, loc):
'''
This function outputs the list with the delimiter given in OFS.
At a name error, it calls __dynamic_module_import so as to import
Expand All @@ -236,7 +236,20 @@ def __print_list(rule, f, glo, loc):
print(OFS.join([str(e) for e in lst]))
except NameError as e:
__dynamic_module_import(e)
__print_list(rule, f, glo, loc)
__print_list_normal(rule, f, glo, loc)


def __print_list_csv(rule, f, glo, loc):
'''
This function outputs the list with the csv format.
'''
try:
lst = eval(rule.action, glo, loc) if rule.action else f[1:]
lst = [ '"' + str(s).replace('"','""') + '"' for s in lst ]
print(",".join(lst))
except NameError as e:
__dynamic_module_import(e)
__print_list_csv(rule, f, glo, loc)


'''
Expand Down Expand Up @@ -396,6 +409,7 @@ if __name__ == "__main__":
'''
__str_mode = __check_option("s")
__csv_mode = __check_option("c")
__csv_output_mode = __check_option("C")
__buffer_mode = __check_option("b")

IFS, IFSREGEX = __get_ifs()
Expand All @@ -416,6 +430,8 @@ if __name__ == "__main__":
else:
__split_fields = __split_fields_null

__print_list = __print_list_csv if __csv_output_mode else __print_list_normal

__modules = __get_header()

for eq in __get_values():
Expand Down
6 changes: 6 additions & 0 deletions test
Original file line number Diff line number Diff line change
Expand Up @@ -412,4 +412,10 @@ com=./opy
[ "$result" = '6' ]
}

@test "csv output mode" {
result=$( echo -ne '1,2,3\n"あ","い"",","う"\n"やや,""こし"",や〜","やや,""こし"",や〜",","\n"もう,"",","いや,"",や"\n' | $com -c -o '|' 4)
result2=$( echo -ne '1,2,3\n"あ","い"",","う"\n"やや,""こし"",や〜","やや,""こし"",や〜",","\n"もう,"",","いや,"",や"\n' | $com -cC 4 | $com -c -o '|' 4)

[ "$result" = "$result2" ]
}

0 comments on commit 5c2092c

Please sign in to comment.