You get a bonus - 1 coin for daily activity. Now you have 1 coin

bash/sh: extracting a substring bounded by given characters (a delimiter) from a string in scripts

Practice



Task: extract a substring with delimiters from an existing string, specifying a certain number. That is, for example, from the string "ABC,DEF,GHI" extract the string "DEF", specifying that it is the 2nd substring and the delimiter is a comma.


For this we will use the cut utility.


a="String1,String2,String3"
echo "${a}" | cut -d ',' -f 2

here:
  • -d : specifies the delimiter character
  • -f : specifies the substring number (starting from 1)

If you need to extract a substring with a TAB delimiter - then you simply do not need to specify the -d parameter, since TAB is the delimiter by default.


Here is another example:
a="This is just a test"
b=`echo "${a}" | cut -d ' ' -f 3`
The output will be "just".

Comments

Guest 31-10-2020
быстро, понятно, рабоче
V.Semenov 28-04-2020
Спасибо! Это - единственный универсальный способ извлечения подстроки. Он работает везде,- от RedHat 7.1 до Ubuntu и Mint. А все остальные типа expr, (substr:n:len) ограниченно работоспособны и явно зависят от версии Bash.

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "LINUX operating system"

Terms: LINUX operating system