Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reformat list string with spaces

Tags:

regex

awk

perl

I have a string list that is printed to the console. I need to convert back it to quoted string.

Assume the sample file is like below

List(UT_LVL_17_CD, UT_LVL_20_CD, 2018 1Q, 2018 2Q, 2018 3Q, 2018 4Q, 2018 FY)
List(UT_LVL_17_CD,UT_LVL_20_CD,2018 1Q,2018 2Q,018 3Q,2018 4Q,2018 FY)
List( UT_LVL_17_CD,    UT_LVL_20_CD,2018 1Q,2018 2Q, 2018 3Q, 2018 4Q, 2018 FY )

For all the 3 combinations above, the output should be

List("UT_LVL_17_CD", "UT_LVL_20_CD", "2018 1Q", "2018 2Q", "2018 3Q", "2018 4Q", "2018 FY")

note that spaces at the start, end or between elements is acceptable.

List(  "UT_LVL_17_CD", "UT_LVL_20_CD", "2018 1Q", "2018 2Q", "2018 3Q", "2018 4Q",    "2018 FY" )

but not within the string value, like below

"     UT_LVL_17_CD"
"UT_LVL_20_CD   ",

the spaces that are already in each element should be preserved "2018 4Q"

I'm trying something like below, but not able to get the correct result.

$ perl -pe ' s/(?<=\()|(?=,)|(?=\))/\"/sg ' list.txt
List("UT_LVL_17_CD", UT_LVL_20_CD", 2018 1Q", 2018 2Q", 2018 3Q", 2018 4Q", 2018 FY")
List("UT_LVL_17_CD",UT_LVL_20_CD",2018 1Q",2018 2Q",018 3Q",2018 4Q",2018 FY")
List(" UT_LVL_17_CD",    UT_LVL_20_CD",2018 1Q",2018 2Q", 2018 3Q", 2018 4Q", 2018 FY ")
$
like image 232
stack0114106 Avatar asked Jul 29 '26 10:07

stack0114106


1 Answers

perl -wpe'
    s{ \(\K ([^)]+) }
     { join ", ", map { s/^\s+|\s+$//g; qq("$_") } split /,/, $1 }ex
' file
like image 186
zdim Avatar answered Aug 01 '26 01:08

zdim