0

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 ?

1
  • What is this data? How do you get this? and who is the receiver for this formatted data? knowing these information would help us provide better and more meaningful solutions Commented Jan 27, 2020 at 13:21

5 Answers 5

2

Don't read lines with for.

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Your desired output looks like JSON, if so you can use for this. E.g:

jq -Rn '[inputs]' Test2.txt

Comments

0

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%, } ]"

Comments

0

a tricky bit of perl:

perl -00 -pe 'chomp; s/\n/, /g; BEGIN {print "[ "} END {print " ]\n"}' Test2.txt

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.