Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain the first letter in a Bash variable?

I have a Bash variable, $word, which is sometimes a word or sentence, e.g.:

word="tiger" 

Or:

word="This is a sentence." 

How can I make a new Bash variable which is equal to only the first letter found in the variable? E.g., the above would be:

echo $firstletter t 

Or:

echo $firstletter T 
like image 542
Village Avatar asked Apr 18 '12 21:04

Village


People also ask

How do I get the first letter of a string in bash?

To access the first character of a string, we can use the (substring) parameter expansion syntax ${str:position:length} in the Bash shell. position: The starting position of a string extraction.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

How do I find the first word in Linux?

In case your string contains newlines | head -n1 will select the first line first before the important commands select the first word from the string passed to it. The would return the first word of every line, not the first word.


1 Answers

word="tiger" firstletter=${word:0:1} 
like image 99
Karoly Horvath Avatar answered Oct 19 '22 10:10

Karoly Horvath