Reputation: 133
I've these data :
2020-01-01-00-00
2020-01-01-06-00
2020-01-01-12-00
2020-01-01-18-00
I would like to display these data like this :
[ 2020-01-01-00-00, 2020-01-01-06-00, 2020-01-01-12-00, 2020-01-01-18-00 ]
I try this :
for i in $(cat Test2.txt)
do
tr -d "\n" <<< $i," "
done
The output is :
2020-01-01-00-00, 2020-01-01-06-00, 2020-01-01-12-00, 2020-01-01-18-00,
Then I try :
for i in $(cat Test2.txt)
do
echo " [ `tr -d "\n" <<< "'$i'"," "` ]"
done
But the output is :
[ '2020-01-01-00-00', ]
[ '2020-01-01-06-00', ]
[ '2020-01-01-12-00', ]
[ '2020-01-01-18-00', ]
Could you show me how to do that ?
Upvotes: 0
Views: 45
Reputation: 15273
In sed
,
$: sed -n '$!H; ${H; x; s/\n/, /g; s/$/ ]\n/; s/^,/[/; p;}' infile
In bash
,
$: dat="$(printf "%s, " $(<infile))"; printf "[ ${dat%, } ]\n";
in 'awk',
$: awk 'BEGIN{ printf "[ "; sep=""; } { printf "%s%s", sep, $0; sep=", "; } END{ print " ]"; }' infile
Upvotes: 0
Reputation: 246774
a tricky bit of perl:
perl -00 -pe 'chomp; s/\n/, /g; BEGIN {print "[ "} END {print " ]\n"}' Test2.txt
Upvotes: 0
Reputation: 7277
Using printf
data="
2020-01-01-00-00
2020-01-01-06-00
2020-01-01-12-00
2020-01-01-18-00
"
printf -v data %s,\ $data
printf "[ ${data%, } ]"
Upvotes: 0
Reputation: 189357
A common arrangement is to use a separator prefix which changes after the first iteration.
prefix='['
while read -r line; do
printf '%s %s' "$prefix" "$line"
prefix=','
done <Test2.txt
printf ' ]\n'
I'll second the suggestion to use a JSON-specific tool if your task is to generate valid JSON, though. This is pesky and somewhat brittle.
Upvotes: 2
Reputation: 50750
Your desired output looks like JSON, if so you can use jq for this. E.g:
jq -Rn '[inputs]' Test2.txt
Upvotes: 1