PJ Bergeron
PJ Bergeron

Reputation: 2998

Cut string with awk

I have a string like that

key2|ex|am||ple

I'd want to get example. I want to get the part after the first pipe and without the other pipes.

For the moment I'm using awk -F"|" '{print $2,$3,$4,$5}' but it's not a good solution.

Upvotes: 2

Views: 38346

Answers (6)

Vijay
Vijay

Reputation: 67211

perl -pe 's/^[^\|]*\|//g;' your_file

Updating after the comment from @Ed

perl -F"|" -ane 'shift @F;print "@F"' your_File

Upvotes: 0

user1461760
user1461760

Reputation:

You can simply set the output field separator and unset the first field:

$ echo 'key2|ex|am||ple' | awk -v FS="|" -v OFS="" '{ $1 = "" ; print }'
example

Upvotes: 2

Ed Morton
Ed Morton

Reputation: 203284

This is a simple substitution on a single line and so a good application for sed:

$ echo 'key2|ex|am||ple' | sed -e 's/[^|]*|//' -e 's/|//g'
example

or if your sed supports EREs:

$ echo 'key2|ex|am||ple' | sed -r 's/^[^|]*[|]|[|]//g'
example

or the equivalent in awk (all awks support EREs):

$ echo 'key2|ex|am||ple' | awk '{gsub(/^[^|]*[|]|[|]/,"")}1'
example

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246774

cut -d '|' -f 2- <<< "$string" | tr -d '|'

I'd write the awk solution this way

awk -F '|' -v OFS="" '{$1=""; print}'

Upvotes: 8

perreal
perreal

Reputation: 97938

Using sed and tr:

echo "key2|ex|am||ple" | sed 's/[^|]*|//' | tr -d '|'

Upvotes: 1

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185025

Try doing this with a C style for loop

 echo 'key2|ex|am||ple' | awk -F'|' '{for (i=2; i<=NF; i++) printf("%s", $i)}'
 example

Upvotes: 6

Related Questions