Article Title: Modify Bash variable content in Linux. Linux is a technology channel of the IT lab in China. Includes basic categories such as desktop applications, Linux system management, kernel research, embedded systems, and open source.
We know two ways to win a variable:
Echo $ HOME echo $ {HOME}
In the echo $ {variable} method, you can also modify the content of the variable. You only need to add some character signs and then use the comparison string to modify the content of the variable. Assume that the variable name is vbird and the content is/home/vbird/testing. x. sh.
◆ 1. Completely present the vbird variable:
Vbird = "/home/vbird/testing. x. sh"
Echo $ {vbird}
/Home/vbird/testing. x. sh
◆ 2. In the vbird variable, compare from the beginning
If it starts with/, all data between two/s is deleted, that is /*/
Echo $ {vbird ##/*/}
Testing. x. sh --/home/vbird/testing/is deleted/
Echo $ {vbird #/*/}
Vbird/testing. x. sh -- only/home/is deleted.
------ In these two examples, if the variable name is followed by two ##, it indicates that the string following ## gets the "longest" segment; if there is only one #, indicates the segment with the "smallest" value. (Self-note: "The smallest segment" indicates the content between the characters closest to the first character from left to right and the same as the first character. The longest part is the opposite)
◆ 3. Answer the question. If it is from the end, delete?
Echo $ {vbird % /*/}
/Home/vbird/testing. x. sh -- none of them are deleted.
Echo $ {vbird % /*}
-------- All deleted
Echo $ {vbird % /*}
/Home/vbird/testing -- only delete the/testing. x. sh part
In this example, we should pay special attention that % compares the meaning of "the last character", so the first one is of course incorrect, because the content of the vbird variable is h rather /. as for %/*, the "Longest/*" is deleted, and %/* is the shortest. (Self-note: the shortest is the same as above. Although % indicates reverse comparison, note that the input in $ {variable} is still in the left-to-right order, that is, the character sequence is the same as that in the variable content. For example:
Echo $ {vbird % t * h}
/Home/vbird/testing/tes -- t. ing. x. sh is deleted.
If yes
Echo $ {vbird % h * t}
/Home/vbird/testing. x. sh -- the output is unchanged (because the comparison is compared with the first character, the first character of the variable content is h, and the first character given in the command is t, does not match the actual variable content .)
◆ 4. Replace testing in the vbird variable with TEST
Echo $ {vbird/testing/TEST}
/Home/vbird/TEST/testing. x. sh
Echo $ {vbird // testing/TEST}
/Home/vbird/TEST. x. sh
If the variable is followed by a slash (/), it indicates that the variable is followed by "replace" and only replaces "first". If it is //, all strings are replaced.