How to implement bash string processing in linux
This article is about how to implement bash string handling in linux. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Get the length of the string
The code is as follows:
Code:
% x = "abcd"
# method 1
Expr length $x
four
# method 2
% echo ${# x}
four
# method 3
% expr "$x": ". *"
four
# help from expr
# STRING: REGEXP anchored pattern match of REGEXP in STRING
Find substring
The code is as follows:
Code:
Expr index $x "b"
two
Expr index $x "a"
one
Expr index $x "b"
two
Expr index $x "c"
three
Expr index $x "d"
four
Get the substring
The code is as follows:
Code:
# method 1
# expr startpos length
Expr substr "$x" 1 3
Abc
Expr substr "$x" 1 5
Abcd
Expr substr "$x" 2 5
Bcd
# method 2
# ${x:pos:lenght}
% echo ${XRO 1}
Bcd
% echo ${XRO 2}
Cd
% echo ${xpurl 0}
Abcd
% echo ${XRV 0RV 2}
Ab
% pos=1
% len=2
% echo ${x:$pos:$len}
Bc
Match regular expression
The code is as follows:
Code:
# print matching length
Expr match $x "."
one
Expr match $x "abc"
three
Expr match $x "bc"
0
Pinch the beginning and end of a string
The code is as follows:
Code:
% x=aabbaarealwwvvww
Echo'${x%w*w}'
Aabbaarealwwvv
Echo'${x%%w*w}'
Aabbaareal
Echo'${x##a*a}'
Lwwvvww
Echo'${x#a*a}'
Bbaarealwwvvww
Where # means pinch, because # on the keyboard is on the left side of $.
Where% means%, because% on the keyboard is on the right side of $.
A single represents a minimum match and two represents a maximum match.
In other words, when there are multiple matching schemes, choose the maximum length or the minimum length of the match.
Replacement of string
The code is as follows:
Code:
% x=abcdabcd
% echo ${x/a/b} # replaces only one
Bbcdabcd
% echo ${x//a/b} # replace all
Bbcdbbcd
You can't use regexp, only *? The way in which files are extended.
Thank you for reading! This is the end of this article on "how to implement bash string processing in linux". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!