SMT
SMT

Reputation: 47

Extracting UUID string from a text using shell script commands

I have a text line as:

host_id -------------------------------------- f5f4d3e7-fdc4-49f2-b32c-13280bc7db66 (1 rows)

And I want to extract only the UUID value within the text using shell script as I need to run this on ubuntu to execute some other commands using the value. I tried using cut command:

cut -d '-' -f2 | cut -d '(' -f1

But couldn't succeed to specify the cut character for before and after of the UUID string.

Upvotes: 2

Views: 2095

Answers (1)

mtnezm
mtnezm

Reputation: 1027

The problem using cut -d'-' in your case is that the field (-f) values you will have to add is not 2 but 38 and above (that's the number of consecutive - symbols in your string), because of how cut works. This is the output you will get if you just set the field 39 (using cut -d'-' -f39):

f5f4d3e7

But also the UUID string you want contains additional hyphens, so if you still want to get it that way (using cut) you will have to expand your field selection, in this case by adding -f39-43. But that just will not solve the problem of showing the string "(1 rows)" after it, so by running cut -d'-' -f39-43 you will get this:

f5f4d3e7-fdc4-49f2-b32c-13280bc7db66 (1 rows)

And that's why you used a second cut filter to just pick the UUID value string. While this is okay, it seems to be pretty much handy using awk, which will solve all these problems in one single command:

cat file.txt | awk '{ print $3 }'

Or if your string is not coming from a file:

echo "host_id -------------------------------------- f5f4d3e7-fdc4-49f2-b32c-13280bc7db66 (1 rows)" | awk '{ print $3 }'

Upvotes: 1

Related Questions