vsingal5
vsingal5

Reputation: 304

Extract stuff between the first pipes in bash?

I want to extract the stuff in between the first two pipes:

| a650f360-a29d-4562-b46f-024fe15aa7dc | emi-ubuntu-12.04.2-server-amd64-08152013           | ACTIVE |

The output should be:

 a650f360-a29d-4562-b46f-024fe15aa7dc 

I have a regex that I was going to use sed with: ^\|\s*(.*?)\s*\|

but according to a regex calculator it gets me the pipes as well. How do I get rid of it?

Upvotes: 0

Views: 129

Answers (3)

Fritz G. Mehner
Fritz G. Mehner

Reputation: 17188

Bash only. In a loop this can be done using an array:

while IFS='|'; read -a line ; do
  echo ${line[1]}            # with leading/trailing blanks
  echo ${line[1]// /}        # without leading/trailing blanks
done < "$infile"

Upvotes: 0

Glen Solsberry
Glen Solsberry

Reputation: 12320

Cut is probably easier to understand than regex. Why not

cut -d\| -f2

?

Upvotes: 5

Jonathan Leffler
Jonathan Leffler

Reputation: 753595

sed 's/^[^|]*|\([^|]*\)|.*/\1/'

That matches any non-pipes at the beginning (nothing in the example data), a pipe, captures the stuff that isn't a pipe, matches another pipe and anything at the end, and replaces it with the captured stuff.

Upvotes: 1

Related Questions