Monday, January 20, 2025
HomeProgrammingHow can you extract a substring from a string in Bash?

How can you extract a substring from a string in Bash?

In Bash, you can extract a substring from a string using parameter expansion. Here’s the syntax:

${string:start_position:length}

string is the variable containing the string.

start_position is the index where the substring begins (0-based).

length is the number of characters to extract (optional).

See also  Simple Java Program to say Hello World

Example:

string=”Hello, World!”
substring=${string:7:5}
echo $substring # Outputs “World”

In this example, the substring starts from position 7 and is 5 characters long. If you omit the length, the substring will extend from the start position to the end of the string.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x