Get the App
SLTechnology News&Howtos  ›  Servers  › 

Unix string interception

Shulou Source: shulou.com Published: 2022-06-03 08:39:31 09月21日 Update

1. Use the method that comes with unix:

${varible##*string} intercepts the string after the last string from left to right

${varible#*string} intercepts the string after the first string from left to right

${varible%%string*} intercepts the string after the last string from right to left

${varible%string*} intercepts the string after the first string from right to left

"*" is just a wildcard. You don't have to.

$test1=123456.txt

$echo ${test1%.txt}

123456

$echo ${test1#*23}

456.txt

$test2=$ {test1%.txt} '.rst'

$echo $test2

123456.rst

2. Use the cut command

$test1=123456.txt

$echo $test1 | cut-f 1-d.

123456

I have a slight question here, why can't you assign this value to another variable? For example:

$test2=echo $test1 | cut-f 1-d.

Ksh: 123456.txt: not found.

$echo test2=$test1 | cut-f 1-d.

Test2=123456

$echo $test2

Test2 has no value here, why?

I suddenly thought of the backquotation marks in shell. The one above the TAB key, the part enclosed by the backquotation marks, will be executed first, and the following test has been done:

$test2= `echo $test1 | cut-f 1-d. `

$echo $test2

123456

$test2= `echo $test1 | cut-f 1-d. ``.rst'

$echo $test2

123456.rst

Success!

Tags: Character string quotation mark success variable just command method question wildcard partial faceted test Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker OPPO Reno Linux Xiaomi Apple