noober
noober

Reputation: 1505

unix - how to create a single string from a list of multiple outputs

I've got a snippet here that i'm running on the command line which creates the following output:

$ { time mysql -u root -N -e "select NOW();" >/dev/null; } 2>&1 | grep real; echo ":localhost:"; date +"%m-%d-%y"
real    0m0.022s
:localhost:
04-28-17

I'd like my output to be a single string like so: (or delimited by whatever I choose as delimiter if possible)

real    0m0.022s :localhost:04-28-17

What command can I use to concat or join to create my string? Thanks.

Upvotes: 3

Views: 131

Answers (2)

twalberg
twalberg

Reputation: 62379

Something like this should work, assuming bash as your shell:

echo "$(grep real < <({ time mysql -u root -N -e 'select NOW();'; } 2>&1)):localhost:$(date +'%m-%d-%y')"

The first $(...) could also be your original { time mysql -u root -N -e 'select NOW();'; } 2>&1 | grep real. I don't see a particularly compelling reason to prefer one way over the other.

The core concept, though, is that doing echo "$(...)" strips trailing newlines off the output of whatever's inside $(...)...

Upvotes: 2

JNevill
JNevill

Reputation: 50034

You can just wrap that whole beast up and send it to sed to wipe out the linefeeds:

 { { time mysql -u root -N -e "select NOW();" >/dev/null; } 2>&1 | grep real; echo ":localhost:"; date +"%m-%d-%y"; } | sed ':a;N;$!ba;s/\n/ /g'

In Action:

$ { { time mysql -u root -N -e "select NOW();" >/dev/null; } 2>&1 | grep real; echo ":localhost:"; date +"%m-%d-%y"; } | sed ':a;N;$!ba;s/\n/ /g'
real    0m0.412s :localhost: 04-28-17

Upvotes: 0

Related Questions