Ozkan
Ozkan

Reputation: 4160

split string containing special characters

This is the string I have:

COUNT(*) 154

The part I need is 154 (the number after the space).

I tried sed and cut commands like for example: for sed:

's/COUNT(\*) //'

So only the number remains. But it doesn't work.

Upvotes: 0

Views: 817

Answers (7)

mklement0
mklement0

Reputation: 437208

Another option:

cut -d' ' -f2 <<<'COUNT(*) 154'

You're telling cut to return the 2nd space-delimited field.

Note that single-quoting the input string ensures its literal use, with no variable interpolation or shell expansions taking place.

Update: To address the original issue:

The OP's sed command, 's/COUNT(\*) //' actually works:

sed 's/COUNT(\*) //' <<< 'COUNT(*) 154'  # -> '154'

Note that sed uses basic regexes by default, so () must NOT be escaped - by contrast, -E expects extended regexes which DO require escaping of ():

sed -E 's/COUNT\(\*\) //' <<< 'COUNT(*) 154'  # -> '154'

That leaves us to wonder (as @shellter suggests) whether the input string is indeed just literal COUNT(*) 154 and doesn't contain other chars. such as \n, \r, t.

An easy way to examine the actual characters is to use:

od -a <<< 'COUNT(*) 154'

This will a character-by-character representation of the input string (strictly speaking: byte-by-byte), with control characters represented symbolically; e.g.: nl for \n, ht for \t, sp for space.

Upvotes: 1

Fritz G. Mehner
Fritz G. Mehner

Reputation: 17188

A Bash solution removing all non-digits:

str='COUNT(*) 154'

echo  "${str//[^0-9]/}"

The output is

154

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 246764

bash's builtin read command can handle this:

$ s='COUNT(*) 154'
$ read a b <<< "$s"
$ echo $b
154

If there are multiple whitespace-separated words, read the string into an array:

$ s='COUNT (*) 154'
$ read -a words <<< "$s"
$ echo "${#words[@]}"
3
$ echo "${words[-1]}"
154

If, as @shelter suggests, your string actually contains a newline instead of a space:

$ s='COUNT(*)
154'
$ { read header; read value; } <<< "$s"
$ echo $value
154

Upvotes: 2

Habit
Habit

Reputation: 31

echo "COUNT(*) 154" | awk -F" " '{print $2}'

echo "COUNT(*) 154" | cut -d" " -f2

Upvotes: 2

suspectus
suspectus

Reputation: 17258

The sed solution:

sed -n 's/COUNT(\*) \([0-9]\+\)/\1/p' your-file

Upvotes: 2

V H
V H

Reputation: 8587

echo "COUNT(*) 154"|awk '{print $NF}'
echo "COUNT(*) 154"|awk '{print $2}'

Upvotes: 2

Donovan
Donovan

Reputation: 15917

Rather crude, but if the COUNT(*) string doesn't change, and you want to use cut you can use:

echo "COUNT(*) 154" | cut -c10-

This will grab anything from the 10th character onward.

Upvotes: 1

Related Questions