How to Get First Word of a String in Bash (With Examples)


Often you may want to get the first word of a string in Bash.

You can use the following methods to do so:

Method 1: Get First Word of String Using read Command

echo " this is a string" | { read first rest ; echo $first ; }

Method 2: Get First Word of String Using awk

echo " this is a string" | awk '{print $1;}'

Note that both of these methods are capable of extracting the first word in a string even if there are leading white spaces in the string.

The following examples show how to use each method in practice.

Example 1: Get First Word in String Using read Command

Suppose that we have the following string:

  • ” this is a string”

And suppose that we would like to extract only the first word “this” from the string.

We can use the following syntax with the read command to do so:

echo " this is a string" | { read first rest ; echo $first ; }

The following screenshot shows how to use this syntax in practice:

Bash get first word of string

Note that we’re able to extract “this” – which represents the first word in the string. 

Also notice that this syntax was capable of extracting the first word in the string even though there was a leading space in the string.

Example 2: Get First Word in String Using awk

Once again suppose that we have the following string:

  • ” this is a string”

And suppose that we would like to extract only the first word “this” from the string.

We can use the following syntax with awk to do so:

echo " this is a string" | awk '{print $1;}'

The following screenshot shows how to use this syntax in practice:

Bash get first word of string using awk

Note that we’re able to extract “this” – which represents the first word in the string. 

Note that the command $1 tells awk to extract only the first word in the string.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Extract Text Between Two Strings
Bash: How to Replace Multiple Characters in String
Bash: How to Replace All Occurrences of String in File

Leave a Reply