What Linux Shell Command Returns a Part of a String

What linux shell command returns a part of a string?

If you are looking for a shell utility to do something like that, you can use the cut command.

To take your example, try:

echo "abcdefg" | cut -c3-5

which yields

cde

Where -cN-M tells the cut command to return columns N to M, inclusive.

Extract substring in Bash

Use cut:

echo 'someletters_12345_moreleters.ext' | cut -d'_' -f 2

More generic:

INPUT='someletters_12345_moreleters.ext'
SUBSTRING=$(echo $INPUT| cut -d'_' -f 2)
echo $SUBSTRING

How to check if a string contains a substring in Bash

You can use Marcus's answer (* wildcards) outside a case statement, too, if you use double brackets:

string='My long string'
if [[ $string == *"My long"* ]]; then
echo "It's there!"
fi

Note that spaces in the needle string need to be placed between double quotes, and the * wildcards should be outside. Also note that a simple comparison operator is used (i.e. ==), not the regex operator =~.

shell script function return a string

The first is calling the function and storing all of the output (four echo statements) into $constr.

Then, after return, you echo the preamble printing result, $constr (consisting of four lines) and the exit message.

That's how $() works, it captures the entire standard output from the enclosed command.

It sounds like you want to see some of the echo statements on the console rather than capturing them with the $(). I think you should just be able to send them to standard error for that:

echo "String1 $1" >&2

How to extract last part of string in bash?

How do you know where the value begins? If it's always the 5th and 6th words, you could use e.g.:

B=$(echo "$A" | cut -d ' ' -f 5-)

This uses the cut command to slice out part of the line, using a simple space as the word delimiter.

Checking if output of a command contains a certain string in a shell script

Test the return value of grep:

./somecommand | grep 'string' &> /dev/null
if [ $? == 0 ]; then
echo "matched"
fi

which is done idiomatically like so:

if ./somecommand | grep -q 'string'; then
echo "matched"
fi

and also:

./somecommand | grep -q 'string' && echo 'matched'


Related Topics



Leave a reply



Submit