Charychap
Charychap

Reputation: 69

How to Substring a string in bash?

I want to cut following string

abcd|xyz

number of characters before and afer pipe "|" symbol can vary.

I know cut command but it requires specific number 'from' and 'to' and i dont think will work here.

Can anyone help?

Upvotes: 0

Views: 34

Answers (1)

Phylogenesis
Phylogenesis

Reputation: 7890

The command cut has the following parameters:

-d, --delimiter=DELIM   use DELIM instead of TAB for field delimiter
-f, --fields=LIST       select only these fields;  also print any line
                            that contains no delimiter character, unless
                            the -s option is specified

Following on from this, the below commands should do what you wish:

echo 'abcd|xyz' | cut -d'|' -f1   # Prints abcd
echo 'abcd|xyz' | cut -d'|' -f2   # Prints xyz

Upvotes: 2

Related Questions