Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first character of a string SHELL

Tags:

linux

sh

I want to first the first character of a string, for example:

$>./first $foreignKey

And I want to get "$"

I googled it and I found some solutions but it concerns only bash and not Sh !

like image 422
03t02 Avatar asked Jan 06 '15 02:01

03t02


3 Answers

Well, you'll probably need to escape that particular value to prevent it being interpreted as a shell variable but, if you don't have access to the nifty bash substring facility, you can still use something like:

name=paxdiablo
firstchar=`echo $name | cut -c1-1`

If you do have bash (it's available on most Linux distros and, even if your login shell is not bash, you should be able to run scripts with it), it's the much easier:

firstchar=${name:0:1}

For escaping the value so that it's not interpreted by the shell, you need to use:

./first \$foreignKey

and the following first script shows how to get it:

letter=`echo $1 | cut -c1-1`
echo ".$letter."
like image 175
paxdiablo Avatar answered Oct 17 '22 02:10

paxdiablo


This should work on any Posix compatible shell (including sh). printf is not required to be a builtin but it often is, so this may save a fork or two:

first_letter=$(printf %.1s "$1")

Note: (Possibly I should have explained this six years ago when I wrote this brief answer.) It might be tempting to write %c instead of %.1s; that produces exactly the same result except in the case where the argument "$1" is empty. printf %c "" actually produces a NUL byte, which is not a valid character in a Posix shell; different shells might treat this case differently. Some will allow NULs as an extension; others, like bash, ignore the NUL but generate an error message to tell you it has happened. The precise semantics of %.1s is "at most 1 character at the start of the argument, which means that first_letter is guaranteed to be set to the empty string if the argument is the empty string, without raising any error indication.

like image 34
rici Avatar answered Oct 17 '22 00:10

rici


Maybe it is an old question. recently I got the same problem, according to POSIX shell manual about substring processing, this is my solution without involving any subshell/fork

a="some string here" printf 'first char is "%s"\n' "${a%"${a#?}"}"

like image 5
win-t Avatar answered Oct 17 '22 02:10

win-t