Shell string operation

Source: Internet
Author: User

Http://www.cnblogs.com/kentyshang/archive/2007/07/11/814279.html

 

Shell string operation

Get Length
Code:

% X = "ABCD"
# Method 1
% Expr length $ x
4
# Method 2
O $
4
# Method 3
% Expr "$ X ":".*"
4
# Expr help
# String: Regexp anchored pattern match of Regexp in string

Search for substrings
Code:

% Expr index $ X "B"
2
% Expr index $ X ""
1
% Expr index $ X "B"
2
% Expr index $ X "C"
3
% Expr index $ X "D"
4

Obtain the substring
Code:

# Method 1
# Expr <string> startpos Length
% Expr substr "$ X" 1 3
ABC
% Expr substr "$ X" 1 5
ABCD
% Expr substr "$ X" 2 5
BCD
# Method 2
# $
O $
BCD
O $
CD
O $
ABCD
O $
AB
% Pos = 1
% Len = 2
O $
BC

Match Regular Expression
Code:

# Print matching length
% Expr match $ X "."
1
% Expr match $ X "ABC"
3
% Expr match $ X "BC"
0

The beginning and end of a string
Code:

% X = aabbaarealwwvvww
O "$"
Aabbaarealwwvv
O "$"
Aabbaareal
O "$"
Lwwvvww
O "$"
Bbaarealwwvvww

Where, # indicates the header, because # on the keyboard is on the left of $.
Here, % indicates % because % on the keyboard is on the right of $.
A single parameter indicates the minimum matching, and a double parameter indicates the maximum matching.
That is to say, when there are multiple matching schemes, select the maximum length or the minimum length of the matching.

String replacement
Code:

% X = abcdabcd
O $ # Replace only one
Bbcdabcd
O $ # Replace all
Bbcdbbcd

Regexp cannot be used, *? File Extension Method

Certificate -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

Processing strings
Including: intercept, connection, match, replace, flip ......
String processing:
1. truncate
Method 1:
Echo $ A | awk '{print substr (, 1, 8 )}'
Substr is a subfunction in the awk. It intercepts the first parameter. It starts from the first character and contains 8 characters in total. If not, it is supplemented from the second character.
Method 2
Echo $ A | cut-b2-8
Cut: process the standard input string
Cut-BN-M: in bytes, starting from n Bytes, take M
Cut-BN, M: the unit is byte. The N and M bytes are intercepted.
Cut-B-n, m: in bytes, intercept 1-N, and the M
-C: the unit is charactor.
-D: Specifies the delimiter. The default Delimiter is tab.
-S: Enable standard input without delimeter
Cut-F1: intercepts 1st Fields
Method 3
A = 123456
Echo $
Method 4
Use sed to extract the last two digits of a string
Echo $ test | SED's // (. */)/(../) $ //'
Truncates the first two digits of a string.
Echo $ test | SED's/^ /(../)/(.*/)//'
Welcome to 007 Computer Information
2. Comparison
There seems to be nothing to compare.
3. Connection
$ A $ B
Or
$ String
4. Flip
Method 1:
Run the rev command
Method 2:
Script implementation
#! /Usr/bin/awk-F
######################################## ########################
# Description: duplicate Rev in awk
######################################## ########################
{
Revline = ""
For (I = 1; I <= length; I ++)
{
Revline = substr (, I, 1) revline
}
}
End {print revline}

5. Match
Grep
Egrep
Fgrep
6. Sort
7. Replace
Bash:
% X = abcdabcd
% Echo $ # Replace only one
Bbcdabcd
% Echo $ # Replace all
Bbcdbbcd
SH:
??
How to replace/
Use SED
Replace all matches
Echo $ test | SED's/XX/yy'
Replace a single match
??
8. Obtain the length of the string:
Bash
$
Or
Expr "$ Var ":'.*'
9. determines whether the string is a number.
10 to obtain the number of repetitions of a character in the string.
Echo $ A | TR "X" "/N" | WC-l
The result is subtracted from 1.
Or echo $ A | awk-F "X" '{print NF-1 }'
11. Obtain the number of repetitions of a string in the string. 007 Computer Information
12. replace all strings in a batch of Files
For I in file_list
Do
VI $ I <-!
: G/xxxx/S // xxxx/g
: WQ
!
Done
13. How to insert one character between every two characters in a string
Use SED
Echo $ test | SED's/../& [insert char]/G'

========================================================== ==========================================

Truncates a string like a professional

Although basename and dirname are good tools, you may sometimes need to perform more advanced string "truncation", not just standard path name operations. You can use the built-in variable extension function of Bash to make it more convincing. Variable extensions of the standard type similar to $ {myvar} have been used. However, bash itself can also execute some convenient string truncation. Take a look at these examples:

Method 1:

$ {Varible # * string} captures the string after the last string from left to right.

$ {Varible # * string} captures the string after the first string from left to right.

$ {Varible % string *} captures the string after the last string from the right to the left

$ {Varible % string *} captures the string after the first string from the right to the left.

"*" Is only a wildcard.

$ Myvar1_foodforthought.jpg
$ Echo $ {myvar # * fo}
Rthought.jpg
$ Echo $ {myvar # * fo}
Odforthought.jpg

In the first example, enter $ {myvar # * fo }. What exactly does it mean? Basically, enter the environment variable name in $ {}, two ##, followed by a wildcard ("* fo "). Bash then obtains myvar, finds the longest substring starting from the string "foodforthought.jpg" and matching the wildcard "* fo", and then intercepts it from the start of the string. It may be difficult to understand at the beginning. To feel how this special "#" option works, let's take a step-by-step look at how Bash completes this extension. First, it searches for the Child string that matches the "* fo" wildcard at the beginning of "foodforthought.jpg. The following are the detected substrings:

F
Fo matches * fo
Foo
Food
Foodf
Foodfo matches * fo
Foodfor
Foodfort
Foodforth
Foodfortho
Foodforthou
Foodforthoug
Foodforthought
Foodforthought. j
Foodforthought.jp
Foodforthought.jpg

After searching for matched strings, we can see that Bash finds two matching strings. It selects the longest match, removes it from the beginning of the initial string, and returns the result.

The second variable extension format shown above looks the same as the first one, but it only uses one "#" -- and bash executes almost the same process. It looks at the same substring series as the first example, but Bash removes the shortest match from the initial string and returns the result. As soon as the sub-string "FO" is found, it removes "FO" from the string and returns "odforthought.jpg ".

This may be confusing. Remember this function in a simple way. When you search for the longest match, use # (because # ratio # Is long ). Use # when searching for the shortest match #. Look, it's not hard to remember! Wait, how do you remember to use the '#' character to remove it from the start of the string? Very easy! Note: On the U.S. keyboard, shift-4 is "$", which is an extension of the bash variable. On the keyboard, close to "$" on the left is "#". In this way, we can see that "#" is at the "Start" of "$", so (according to our memory), "#" removes characters from the start of a string. You may want to ask: how to remove characters from the end of a string. If you guess we use the character ("%) next to" $ "on the U.S. keyboard, you can guess it. Here are some simple examples to explain how to cut the end of a string:

$ Myfoo = "chickensoup.tar.gz"
$ Echo $ {myfoo % .*}
Chickensoup
$ Echo $ {myfoo % .*}
Chickensoup.tar

As you can see, except for removing the matching wildcard from the end of the string, the % and % variable extension options work the same way as the # And # variables. Note: If you want to remove the special character string from the end, you do not need to use the "*" character:

Myfood = "Chickensoup"
$ Echo $ {myfood % soup}
Chicken

In this example, "%" or "%" is not important because only one matching exists. Remember: if you forget to use "#" or "%", take a look at the 3, 4, and 5 keys on the keyboard and guess them.

Method 2: $ {Varible: N1: N2}: intercept the string from N1 to N2.

You can use another form of variable extension to select a special character string based on the specific character offset and length. Enter the following lines in Bash:

$ Exclaim = Cowabunga
$ Echo $ {exclaim: 0: 3}
Cow
$ Echo $ {exclaim: 3: 7}
Abunga

String Truncation in this form is very simple. You only need to use a colon to separate the start character and the length of the substring.

Apply string Truncation

Now we have learned all about string truncation. Below is a simple and short shell script. Our script will accept a file as the independent variable, and then print: whether the file is a tar file. To determine whether it is a tar file, the search mode ". tar" will be found at the end of the file ". As follows:

Mytar. Sh -- a simple script

#! /Bin/bash

If ["$ {1 # *.}" = "tar"]
Then
Echo this appears to be a tarball.
Else
Echo at first glance, this does not appear to be a tarball.
Fi

Run this script, input it to the mytar. Sh file, and enter "chmod 755 mytar. Sh" to generate an executable file. Then, perform the tar file experiment as follows:

$./Mytar. Sh thisfile.tar
This appears to be a tarball.
$./Mytar. Sh thatfile.gz
At first glance, this does not appear to be a tarball.

Yes, it runs successfully, but it is not practical. Before making it more practical, let's take a look at the "if" statement used above. A boolean expression is used in the statement. In bash, the "=" comparison operator checks whether the strings are equal. In bash, all boolean expressions are enclosed in square brackets. But what is a Boolean expression actually testing? Let's take a look at the left side. Based on the string truncation knowledge learned above, "$ {1 ##*.} "Remove the longest part starting from the string contained in environment variable" 1 "*. "Match and return results. This will return all parts after the last "." In the file. Obviously, if the object ends with ". tar", the result is "tar" and the condition is true.

You may wonder what the "1" environment variable at the beginning is. Very simple -- $1 is the first command line independent variable passed to the script, $2 is the second, and so on.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.