HK2432
HK2432

Reputation: 133

Change ouput for loop in bash

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

Answers (5)

Paul Hodges
Paul Hodges

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

glenn jackman
glenn jackman

Reputation: 246774

a tricky bit of perl:

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

Upvotes: 0

Ivan
Ivan

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

tripleee
tripleee

Reputation: 189357

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.

Upvotes: 2

oguz ismail
oguz ismail

Reputation: 50750

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

jq -Rn '[inputs]' Test2.txt

Upvotes: 1

Related Questions