Skip to Content
Linux Shell Scripting Cookbook - Third Edition
book

Linux Shell Scripting Cookbook - Third Edition

by Clif Flynt, Sarath Lakshman, Shantanu Tushar
May 2017
Beginner
552 pages
28h 47m
English
Packt Publishing
Content preview from Linux Shell Scripting Cookbook - Third Edition

How to do it...

Let's get into the tasks.

Replace some text from a variable:

    $ var="This is a line of text"
    $ echo ${var/line/REPLACED}
    This is a REPLACED of text"

The line word is replaced with REPLACED.

We can produce a substring by specifying the start position and string length, using the following syntax:

    ${variable_name:start_position:length}

Print from the fifth character onwards:

    $ string=abcdefghijklmnopqrstuvwxyz
    $ echo ${string:4}
    efghijklmnopqrstuvwxyz

Print eight characters starting from the fifth character:

    $ echo ${string:4:8}
    efghijkl

The first character in a string is at position 0. We can count from the last letter as -1. When -1 is inside a parenthesis, (-1) is the index for the last letter:

    echo ${string:(-1)} ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering Linux Shell Scripting - Second Edition

Mastering Linux Shell Scripting - Second Edition

Mokhtar Ebrahim, Andrew Mallett

Publisher Resources

ISBN: 9781785881985