Advanced operating string bash5 ---- 2

1, the command expr: evaluate expressions (support string manipulation and pattern matching string expression is higher than the priority of the numerical expressions and logic expressions.)

  SYNOPISIS

    expr EXPRESSITONS

    expr OPTION

  expr ARG1 {+ - * / | & < <= > >= != %} ARG2 

  expr STRIGN: REGEXP == expr match "STRING" 'REGEXP' (if successful returns a match to the number of words, may also be used to calculate the length of the string)

  substr STRING POS (postion) LENGTH (see substring extraction 2)

  index STRING CHARS # C-like inside the strchr, when the first character to see that returns the number of bytes

  length STRING (string length see below)

  + TOKEN: TOKEN will be parsed as normal string, or even TOKEN like MATCH operator "/" as the keyword. This makes the 'expr length + "$ x"' or 'expr + "$ x":' * / \ '' can normally be tested, even if the value "$ x" could be '/' or '. (\.) index 'keyword. This operator is a GUN extension.

More details can be seen Gangster Bowen .

String length: Method 1: echo `expr length $ Stringname`

      法2:echo ${#Stringname}

      法3:echo `expr "$Stringname" : '.*'`  ==  expr "$Stringname" : '.*'

 

Copy example, inserting a blank line between paragraphs of the text file

! # / bin / the bash 
 # paragraph-space.sh 

 # in a single-spaced text file insert blank lines. 
 # the Usage: $ 0 <FILENAME 

 minlen = # 45 may be required to change this value. 
 # assuming that the length is less than $ row minlen the length of time specified 
 # + was considered the end of this paragraph. 

 as much while read line # and provide input file line ... 
 do 
 echo "$ line" # enter the read line itself. 

 len = $ {# line } 
 IF [ "$ len" -LT-"$ minlen"] 
 the then # echo in a short line (Translator's Note: i.e. less than $ minlen line characters). Add a blank line back 
 Fi 
 DONE 

 Exit 0

  This is an example on the books, it is clear that can not be executed directly, but provides us with an idea. How to paragraphs (a length of less than 45 passages) add a blank line intermediate

First read still need to understand the usage of this function:

First read and inside the shell of a function read is not the same, it is read from a stdio in a high-level programming commonly used functions. We usually use the man read this read unistd.h see is the inside of the read function. If you want to see the shell read usage usually read --help (I may think so, there is a problem we welcome comments criticism).

Then "read --help" is so described:

  read: read [-ers] [-a array] [-d delim] [-i text] [-n nchar] [-p prompt] [-t timeout] [-u fd] [name ...]

  : -A parameter is an array behind. -d delimiter into delim, according to 'delim' instead of to the transport branch. -n followed by the number, length defines the input text. -P output connected back as the message PROMPT. -T take the number of seconds behind, on behalf of the wait time. -u read from fd in.

    Read a line from the standard input and split it into fields.

The above is the command line using the stdin '<' FILENAME to redirect, and then to use echo to stdout inside.

Here are a few changes in the way to his deformed it:

  1, can be above the line 11 while read line into a cat FILENAME (you can also use absolute paths) | while read line. So no need to enter the command line bash Scription.sh <FILENAME

  2, if the result is output to filename2 want, you can enter the command bash Scription.sh <FILENAME1> FILENAME2

  3, it also changed the line 19 above: done> FILENAME2

  4, may also be used to represent a file descriptor, [i] <> filename opens the file filename to read and write, the file descriptor i and allocated to the file. If the filename does not exist, he would have been created, then read -u fd ARG

 

2, substring extraction, substring deleted, replaced substring

$ {String: position}: In the start position of substring extraction position $, $ length length (length in the back position can be added or not added).

2.1, if $ string is "*" or "@", it will start extracting from $ position location parameters

2.2, string extraction time is 0-based indexing

2.3, position is negative when is the reciprocal, but need to add parentheses,

EG:

stringZ=abcABC123ABCabc

echo ${stringZ:0}  #abcABC123ABCabc

echo ${stringZ:7:3}  #23A

echo $ {stringZ: (- 4)} #Cabc. 4 penultimate start? Note that bracketed the escape, if not possible for the $ {stringZ: -default} as the

{*: 2} echo $ # print the second and the following parameters

 

expr substr $string $position $length

EG:  echo `expr substr $stringZ 1 2`  #12

expr match "$ string" '\ ($ substring \)' == expr "$ string": '\ ($ substring \)' are extracted substring

Unlike returns the substring length expr match "$ string" '$ substring' == expr "$ string": '$ substring', less two escaped parentheses. Plus without echo effect is the same.

Extract substring from the end:

match expr "$ String" ' *. == expr "$ String" \ ($ substring \)': ' *. [more before the parentheses "*."] \ ($ substring \)'

 

Child skewer Delete

$ {String # substring} truncated shortest match the string from the start position of the substring $

$ {String ## substring} string from the head position of the substring starts truncated longest $

$ {String% substring} starts from the end of the shortest truncated

$ {String %% substring} starts from the end of the longest amputated

 

Alternatively substring

$ {string / substring / replacement} $ Replacement used to replace the first match the substring $

$ {string // substring / replaement} $ Replacement used to replace all match the substring $

$ {String / # substring / replaement} If a match beginning Replacement $, $ Replacement is used to replace the substring matching $

$ {String /% substring / replaement} $ Replacement If the end of the matching, is used to replace Replacement $ $ match the substring

 

Image conversion:

1, on the Netpbm

Netpbm is a good use of very powerful command image processing program (first converted into pnm png format, and then converted into bmp.pnm pnm an original image is a storage format under LINUX, WINDOWS under the similar BMP). the image is particularly suitable for batch processing, in particular in cooperation with SHELL LINUX.

 About netpbm related programs can be found at this site: http: //www.linuxguruz.com/man-pages/ topic = pnm?

 jpg full name is JPEG [Joint Photo graphic Experts Group]. JPEG image to store a single 24-bit color bitmaps. JPEG is a platform-independent format that supports the highest levels of compression, however, this compression is lossy. Incremental JPEG file support interlaced.

So for converting Linux in jpg or bmp files into ppm.pnm, pbm can use the program Netpbm library.

Here we will be converted to jpg pnm. Program uses jpegtopnm.

E-book which is given to Macpaint converted into a shell script pbm

! 1 # / bin / bash
2 # cvt.sh:
3 # All MacPaint format image files in a directory are converted to "pbm" all kinds of image files.
4
5 # use "netpbm" package "macptopbm "conversion program,
6 # + this program mainly by Brian Henderson ([email protected]) to maintain.
7 # Netpbm the vast majority of Linux distributions standard kit.
8
9 macptopbm of the OPERATION =
10 = SUFFIX PBM # new file name suffix.
11
12 IF [-n "$ 1"]
13 the then
14 directory = $ 1 # If the directory name as a parameter passed to the script ...
15 the else
16 directory = $ PWD # otherwise use the current working directory.
fi 17
18
19 # assumes that all files in the target directory are MacPaint image file formats,
20 # + and are based on ".mac". as the file name suffix
21
22 in $ directory for file / file name matching * # ( the globbing filename).
23 is do
24% filename file = $ {.} * C # remove the file name ".mac"Suffix
25 # + ( '. * C ' will match
+ # 26 between any string '' and 'C').
27 $ $ File the OPERATION> "$ filename. $ SUFFIX"
28 # the results are redirected to the new file.
29 RM # -f $ File Conversion after deleting the original file.
30 echo "$ filename. $ SUFFIX" # stdout output file from the converted file name.
31 DONE
32
33 Exit 0

 

On my computer find / -name command "* .jpg"

Jpg files found many, but no mac file. At the same time I do not want to delete the source files, but the files into another format in the folder. I modified the code as follows:

#! / bin / bash 

 # use "netpbm" package "jpegtopnm" program to convert, 
 # + this program mainly by Brian Henderson ([email protected]) to maintain. 
 # Netpbm the vast majority of Linux distributions version of the standard kit. 

 of the OPERATION = jpegtopnm 
 sUFFIX = # PNM new file name suffix. 

 IF [-n "$ 1"] 
 the then 
 directory = $ 1 # If the directory name as a parameter passed to the script ... 
 the else 
 directory = $ PWD # otherwise use the current working directory. 
 fi 
IF [-n "$ 2"] 
the then 
  redir = $ PWD / $ 2 # If you accept the directory passed as a parameter to the script 
the else 
  mkdir Dirpnm 
   redir = $ PWD / Dirpnm 
fi 
 # assumes that all files in the target directory is MacPaint format image file, 
 # + and are based on ".mac". as the file name suffix 

 for file in $ directory / * # matching filename (filename the globbing). 
 do 
 filename file% = $ {.} * G # removed ".jpg" file namesuffix
 # + ( '. * C' will match 
 # + '.Any string between a 'and' c ').
 = `basename $ filename` recv 
Exec 9> $ redir / $ recv. $ SUFFIX # bind to the directory file descriptor 
$ OPERATION $ file> & 9 # redirected to 9, note preceded by & 
 # to redirect the results to a new file. 
after # rm -f $ file # conversion to delete the original file. does not remove the 
 echo "$ filename. $ SUFFIX" # stdout output file name from the converted file. 
 DONE 

 Exit 0

 

1, the write process sequence : first, to make it clear how to redirect. May be used   exec [n]> filename  to redirect. If not, then he created. There is also a [n] <> filename does not come out with

2. Note that the filename is the filename in the directory contains the absolute path variable. If we need to translate in another path, you only need to go basename then redirected in another folder.

3, the shell script in order to learn if the intention is to clip $ String {string% substring} will cut off the end of the shortest of the substring. (Truncated at the beginning of the longest substring with ##, beginning with a minimum #) and where the substring = ". * G" is JPG (seemingly this operation may be done with a basename)

 

 

3, used to process the character string awk

awk is a full-featured text processing language with a syntax similar to C's. He has a set of operators and capability set, talk about the most useful in a small part of the shell here.

The Awk passed in per line into fields. By default, a domain refers to the use of a continuous string separated by whitespace, but we can modify the properties to change delimiter. Awk parses and operates on each of the divided domain because of this characteristic, so awk ideal for handling structured text files - in particular, the table - the data is organized into a unified block, such as rows and columns.

Strong reference (single quote) and curly brackets enclose awk shell script snippet

eg:  echo one two | awk '{print $2}'  --->  #two

 

Guess you like

Origin www.cnblogs.com/SsoZhNO-1/p/9315871.html