官术网_书友最值得收藏!

  • Bash Cookbook
  • Ron Brash Ganesh Naik
  • 306字
  • 2021-07-23 19:17:36

Striping/altering/sorting/deleting/searching strings with Bash only

So far, we have seen inkling of the power of commands available in Linux, and some of these are among the most powerful: sed and grep. However, while we can easily use these commands together, sed by itself or even using another very useful command called awk, we can leverage Bash itself to shave time and reduce external dependencies in a portable way!

So, how can we do this? Let's begin with a few examples using this Bash syntax:

#!/bin/bash
# Index zero of VARIABLE is the char 'M' & is 14 bytes long
VARIABLE="My test string"
# ${VARIABLE:startingPosition:optionalLength}
echo ${VARIABLE:3:4}

In the preceding example, we can see a special way of calling special substring functionality using ${...} , where VARIABLE is a string variable within your script (or even global), and then the following variable is the :. After the :, there is the startingPosition parameter (remember that strings are just arrays of characters and each character can be addressed by index), and there is another optional semicolon and length parameter (optionalLength). 

If we ran this script, the output would be:

$ bash script.sh
test

How is this possible, you may ask? Well, its possible with Bash's equivalent of substr (a function in C and many other programming languages), and this is achieved through the usr of the ${...}syntax. This tells bash to look inside for a variable named VARIABLE and then for two parameters: to start at byte/character 3 (technically 4 because arrays start at element 0 in Bash) and a length of 4 (to print only four characters). The result of the echo is test.

Can we do more with this, such as removing the last character? Deleting words? Searching? Of course, and all of this is covered in this recipe!

主站蜘蛛池模板: 黎平县| 睢宁县| 吴堡县| 易门县| 涿州市| 永年县| 阜城县| 屏边| 长春市| 襄汾县| 汕头市| 罗山县| 新余市| 沛县| 墨脱县| 卢氏县| 繁昌县| 克什克腾旗| 内乡县| 翼城县| 潼南县| 清流县| 神池县| 紫阳县| 同江市| 宜兰县| 鹤壁市| 沾化县| 定西市| 东乡县| 顺平县| 漯河市| 南充市| 新巴尔虎右旗| 吉木乃县| 惠州市| 花莲市| 北票市| 湄潭县| 常州市| 无为县|