Recent Changes - Search:

Basics

Languages

Tools

OS

Resources

PmWiki

pmwiki.org

edit SideBar

ParsingStrings

Since Bash is a language built around strings, it is quite easy to handle them. One really neat thing is the ability to loop using the words in a variable. Like:

Sentence="This is a bunch of words."
for word in $Sentence ; do echo $word ; done
-> This
-> is
-> a
-> bunch
-> of
-> words.

Getting a character out of a string

Strings are a series of characters. As such, if you know the position of the character(s) you want, you can use:

${var:iFirst:nChar}

where iFirst is the index of the first character to be extracted (starting from 0), and nChar is the number of characters to extract (use 1 to get only the character at iFirst).

You can get everything from a given position by not providing a length of selection:

${var:iFirst}

Getting a word out of a string

In order to get a specific word from a string variable, the cut function can be used:

echo $Sentence | cut -d ' ' -f 4
-> bunch

where the -d option defines the delimiter (here a space in order to distinguish words) and the -f option gives the rank of the word (here the 4th word).

Edit - History - Print - Recent Changes - Search
Page last modified on May 09, 2016, at 05:38 PM