Linux常用命令shell常用知识 。。。。面试被虐之后,吐血整理。。。。

Linux三剑客&常用命令&shell常识

  • Linux三剑客
    • grep - print lines matching a pattern
    • sed - stream editor for filtering and transforming text
    • awk
      • man awk
  • Linux常用命令
    • dd命令
    • ssh命令
    • tar命令
    • curl命令
    • top命令
    • tr命令
    • xargs命令
    • sort命令
    • du/df/free命令
  • shell 知识
    • function的使用

Linux三剑客

grep - print lines matching a pattern

本人常用的grep参数:

  1. -i 忽略大小写 grep -i 'hello' **.txt **.c **.h
  2. -e 多条件过滤 grep -e 'hello' -e 'world' **.txt过滤出包含hello和world的行
  3. -E 支持扩展的正则表达 grep -E 'hello|world' **.txt=grep -e 'hello' -e 'world' **.txt
  4. -v 选中不匹配的行(反选)grep -v 'hello' *.txt 选出没有hello的行
  5. -H 打印文件名
  6. -n 打印行号
sx@sx-virtual-machine:~$ grep -EnH 'DESCRIPTION|OPTIONS' awk_man.txt
awk_man.txt:10:DESCRIPTION
awk_man.txt:21:OPTIONS
sxhan@sxhan-virtual-machine:~$
  1. -A n 打印文本及其后n行
sx@sx-virtual-machine:~$ grep -EnH -A 2 'DESCRIPTION|OPTIONS' awk_man.txt
awk_man.txt:10:DESCRIPTION
awk_man.txt-11-       mawk is an interpreter for the AWK Programming Language.  The AWK language is useful for manipulation of data files, text retrieval and processing, and for prototyp‐
awk_man.txt-12-       ing and experimenting with algorithms.  mawk is a new awk meaning it implements the AWK language as defined in Aho, Kernighan and  Weinberger,  The  AWK  Programming
--
awk_man.txt:21:OPTIONS
awk_man.txt-22-       -F value       sets the field separator, FS, to value.
awk_man.txt-23-
sx@sx-virtual-machine:~$
  1. -B n 打印文本及其前n行
sx@sx-virtual-machine:~$ grep -EnH -B 2 'DESCRIPTION|OPTIONS' awk_man.txt
awk_man.txt-8-       mawk [-W option] [-F value] [-v var=value] [-f program-file] [--] [file ...]
awk_man.txt-9-
awk_man.txt:10:DESCRIPTION
--
awk_man.txt-19-       onymous with lines.  Each record is compared against each pattern and if it matches, the program text for {action} is executed.
awk_man.txt-20-
awk_man.txt:21:OPTIONS
sx@sx-virtual-machine:~$
  1. -c 统计输出的行数
  2. 其他用法见 grep --help or man grep 的输出内容
sx@sx-virtual-machine:~$ grep --help
用法: grep [选项]... PATTERN [FILE]...
Search for PATTERN in each FILE.
Example: grep -i 'hello world' menu.h main.c

Pattern selection and interpretation:
  -E, --extended-regexp     PATTERN is an extended regular expression
  -F, --fixed-strings       PATTERN is a set of newline-separated strings
  -G, --basic-regexp        PATTERN is a basic regular expression (default)
  -P, --perl-regexp         PATTERN is a Perl regular expression
  -e, --regexp=PATTERN      用 PATTERN 来进行匹配操作
  -f, --file=FILE           从 FILE 中取得 PATTERN
  -i, --ignore-case         忽略大小写
  -w, --word-regexp         强制 PATTERN 仅完全匹配字词
  -x, --line-regexp         强制 PATTERN 仅完全匹配一行
  -z, --null-data           一个 0 字节的数据行,但不是空行

杂项:
  -s, --no-messages         不显示错误信息
  -v, --invert-match        选中不匹配的行
  -V, --version             显示版本信息并退出
      --help                显示此帮助并退出

Output control:
  -m, --max-count=NUM       stop after NUM selected lines
  -b, --byte-offset         print the byte offset with output lines
  -n, --line-number         print line number with output lines
      --line-buffered       flush output on every line
  -H, --with-filename       print file name with output lines
  -h, --no-filename         suppress the file name prefix on output
      --label=LABEL         use LABEL as the standard input file name prefix
  -o, --only-matching       只显示匹配PATTERN 部分的行
  -q, --quiet, --silent     不显示所有常规输出
      --binary-files=TYPE   设定二进制文件的TYPE 类型;
                            TYPE 可以是`binary', `text', 或`without-match'
  -a, --text                等同于 --binary-files=text
  -I                        等同于 --binary-files=without-match
  -d, --directories=ACTION  读取目录的方式;
                            ACTION 可以是`read', `recurse',或`skip'
  -D, --devices=ACTION      读取设备、先入先出队列、套接字的方式;
                            ACTION 可以是`read'或`skip'
  -r, --recursive           等同于--directories=recurse
  -R, --dereference-recursive       同上,但遍历所有符号链接
      --include=FILE_PATTERN  只查找匹配FILE_PATTERN 的文件
      --exclude=FILE_PATTERN  跳过匹配FILE_PATTERN 的文件和目录
      --exclude-from=FILE   跳过所有除FILE 以外的文件
      --exclude-dir=PATTERN  跳过所有匹配PATTERN 的目录。
  -L, --files-without-match  print only names of FILEs with no selected lines
  -l, --files-with-matches  print only names of FILEs with selected lines
  -c, --count               print only a count of selected lines per FILE
  -T, --initial-tab         make tabs line up (if needed)
  -Z, --null                print 0 byte after FILE name

文件控制:
  -B, --before-context=NUM  打印文本及其前面NUM 行
  -A, --after-context=NUM   打印文本及其后面NUM 行
  -C, --context=NUM         打印NUM 行输出文本
  -NUM                      same as --context=NUM
      --color[=WHEN],
      --colour[=WHEN]       use markers to highlight the matching strings;
                            WHEN is 'always', 'never', or 'auto'
  -U, --binary              do not strip CR characters at EOL (MSDOS/Windows)

When FILE is '-', read standard input.  With no FILE, read '.' if
recursive, '-' otherwise.  With fewer than two FILEs, assume -h.
Exit status is 0 if any line is selected, 1 otherwise;
if any error occurs and -q is not given, the exit status is 2.

sed - stream editor for filtering and transforming text

常用参数:

  1. -i 对文件原地编辑 sed -i 's/old_str/new_str/g **.txt 将**.txt文件中所有的old_str替换成new_str;s表示替换操作,g表示全局替换

这也是前两天面试官问我的问题,我没回答上来。。。。。
前几年真的用过sed,但也是真的忘了。。。😢😶

Tips:其他的详细用法,以后有空再更新。。。

sx@sx-virtual-machine:~$ sed --help
用法: sed [选项]... {脚本(如果没有其他脚本)} [输入文件]...

  -n, --quiet, --silent
                 取消自动打印模式空间
  -e 脚本, --expression=脚本
                 添加“脚本”到程序的运行列表
  -f 脚本文件, --file=脚本文件
                 添加“脚本文件”到程序的运行列表
  --follow-symlinks
                 直接修改文件时跟随软链接
  -i[SUFFIX], --in-place[=SUFFIX]
                 edit files in place (makes backup if SUFFIX supplied)
  -l N, --line-length=N
                 指定“l”命令的换行期望长度
  --posix
                 关闭所有 GNU 扩展
  -E, -r, --regexp-extended
                 use extended regular expressions in the script
                 (for portability use POSIX -E).
  -s, --separate
                 consider files as separate rather than as a single,
                 continuous long stream.
      --sandbox
                 operate in sandbox mode.
  -u, --unbuffered
                 从输入文件读取最少的数据,更频繁的刷新输出
  -z, --null-data
                 使用 NUL 字符分隔各行
      --help     打印帮助并退出
      --version  输出版本信息并退出

如果没有 -e, --expression, -f 或 --file 选项,那么第一个非选项参数被视为
sed脚本。其他非选项参数被视为输入文件,如果没有输入文件,那么程序将从标准
输入读取数据。

awk

man awk

Tips:awk的详细用法,以后有空再更新。。。

MAWK(1)                                                                         USER COMMANDS                                                                        MAWK(1)

NAME
       mawk - pattern scanning and text processing language

SYNOPSIS
       mawk [-W option] [-F value] [-v var=value] [--] 'program text' [file ...]
       mawk [-W option] [-F value] [-v var=value] [-f program-file] [--] [file ...]

DESCRIPTION
       mawk is an interpreter for the AWK Programming Language.  The AWK language is useful for manipulation of data files, text retrieval and processing, and for prototyp‐
       ing and experimenting with algorithms.  mawk is a new awk meaning it implements the AWK language as defined in Aho, Kernighan and  Weinberger,  The  AWK  Programming
       Language,  Addison-Wesley  Publishing, 1988.  (Hereafter referred to as the AWK book.)  mawk conforms to the Posix 1003.2 (draft 11.3) definition of the AWK language
       which contains a few features not described in the AWK book,  and mawk provides a small number of extensions.

       An AWK program is a sequence of pattern {action} pairs and function definitions.  Short programs are entered on the command line usually enclosed in  '  '  to  avoid
       shell  interpretation.   Longer programs can be read in from a file with the -f option.  Data  input is read from the list of files on the command line or from stan‐
       dard input when the list is empty.  The input is broken into records as determined by the record separator variable, RS.  Initially, RS = "\n" and records  are  syn‐
       onymous with lines.  Each record is compared against each pattern and if it matches, the program text for {action} is executed.

OPTIONS
       -F value       sets the field separator, FS, to value.

       -f file        Program text is read from file instead of from the command line.  Multiple -f options are allowed.

       -v var=value   assigns value to program variable var.

       --             indicates the unambiguous end of options.

       The above options will be available with any Posix compatible implementation of AWK, and implementation specific options are prefaced with -W.  mawk provides six:

       -W version     mawk writes its version and copyright to stdout and compiled limits to stderr and exits 0.

       -W dump        writes an assembler like listing of the internal representation of the program to stdout and exits 0 (on successful compilation).

       -W interactive sets unbuffered writes to stdout and line buffered reads from stdin.  Records from stdin are lines regardless of the value of RS.

       -W exec file   Program text is read from file and this is the last option. Useful on systems that support the #!  "magic number" convention for executable scripts.

       -W sprintf=num adjusts the size of mawk's internal sprintf buffer to num bytes.  More than rare use of this option indicates mawk should be recompiled.

       -W posix_space forces mawk not to consider '\n' to be space.

       The short forms -W[vdiesp] are recognized and on some systems -We is mandatory to avoid command line length limitations.

THE AWK LANGUAGE
   1. Program structure
       An AWK program is a sequence of pattern {action} pairs and user function definitions.

       A pattern can be:
              BEGIN
              END
              expression
              expression , expression

       One,  but  not  both, of pattern {action} can be omitted.   If {action} is omitted it is implicitly { print }.  If pattern is omitted, then it is implicitly matched.
       BEGIN and END patterns require an action.

       Statements are terminated by newlines, semi-colons or both.  Groups of statements such as actions or loop bodies are blocked via { ... } as in C.  The last statement
       in a block doesn't need a terminator.  Blank lines have no meaning; an empty statement is terminated with a semi-colon. Long statements can be continued with a back‐
       slash, \.  A statement can be broken without a backslash after a comma, left brace, &&, ||, do, else, the right parenthesis of an if, while or for statement, and the
       right parenthesis of a function definition.  A comment starts with # and extends to, but does not include the end of line.

       The following statements control program flow inside blocks.

              if ( expr ) statement

              if ( expr ) statement else statement

              while ( expr ) statement

              do statement while ( expr )

              for ( opt_expr ; opt_expr ; opt_expr ) statement

              for ( var in array ) statement

              continue

              break

   2. Data types, conversion and comparison
       There  are  two  basic data types, numeric and string.  Numeric constants can be integer like -2, decimal like 1.08, or in scientific notation like -1.1e4 or .28E-3.
       All numbers are represented internally and all computations are done in floating point arithmetic.  So for example, the expression 0.2e2 == 20 is true  and  true  is
       represented as 1.0.

       String constants are enclosed in double quotes.

                                                                  "This is a string with a newline at the end.\n"

       Strings can be continued across a line by escaping (\) the newline.  The following escape sequences are recognized.

            \\        \
            \"        "
            \a        alert, ascii 7
            \b        backspace, ascii 8
            \t        tab, ascii 9
            \n        newline, ascii 10
            \v        vertical tab, ascii 11
            \f        formfeed, ascii 12
            \r        carriage return, ascii 13
            \ddd      1, 2 or 3 octal digits for ascii ddd
            \xhh      1 or 2 hex digits for ascii  hh

       If you escape any other character \c, you get \c, i.e., mawk ignores the escape.

       There  are  really three basic data types; the third is number and string which has both a numeric value and a string value at the same time.  User defined variables
       come into existence when first referenced and are initialized to null, a number and string value which has numeric value 0 and string value "".   Non-trivial  number
       and string typed data come from input and are typically stored in fields.  (See section 4).

       The type of an expression is determined by its context and automatic type conversion occurs if needed.  For example, to evaluate the statements

            y = x + 2  ;  z = x  "hello"

       The  value  stored  in variable y will be typed numeric.  If x is not numeric, the value read from x is converted to numeric before it is added to 2 and stored in y.
       The value stored in variable z will be typed string, and the value of x will be converted to string if necessary and concatenated  with  "hello".   (Of  course,  the
       value  and  type  stored  in  x is not changed by any conversions.)  A string expression is converted to numeric using its longest numeric prefix as with atof(3).  A
       numeric expression is converted to string by replacing expr with sprintf(CONVFMT, expr), unless expr can be represented on the host machine as an exact integer  then
       it  is  converted  to sprintf("%d", expr).  Sprintf() is an AWK built-in that duplicates the functionality of sprintf(3), and CONVFMT is a built-in variable used for
       internal conversion from number to string and initialized to "%.6g".  Explicit type conversions can be forced, expr "" is string and expr+0 is numeric.

       To evaluate, expr1 rel-op expr2, if both operands are numeric or number and string then the comparison is numeric; if both operands  are  string  the  comparison  is
       string; if one operand is string, the non-string operand is converted and the comparison is string.  The result is numeric, 1 or 0.

       In  boolean  contexts  such as, if ( expr ) statement, a string expression evaluates true if and only if it is not the empty string ""; numeric values if and only if
       not numerically zero.

   3. Regular expressions
       In the AWK language, records, fields and strings are often tested for matching a regular expression.  Regular expressions are enclosed in slashes, and

            expr ~ /r/

       is an AWK expression that evaluates to 1 if expr "matches" r, which means a substring of expr is in the set of strings defined by r.  With no  match  the  expression
       evaluates to 0; replacing ~ with the "not match" operator, !~ , reverses the meaning.  As  pattern-action pairs,

            /r/ { action }   and   $0 ~ /r/ { action }

       are  the same, and for each input record that matches r, action is executed.  In fact, /r/ is an AWK expression that is equivalent to ($0 ~ /r/) anywhere except when
       on the right side of a match operator or passed as an argument to a built-in function that expects a regular expression argument.

       AWK uses extended regular expressions as with egrep(1).  The regular expression metacharacters, i.e., those with special meaning in regular expressions are

             ^ $ . [ ] | ( ) * + ?

       Regular expressions are built up from characters as follows:

              c            matches any non-metacharacter c.

              \c           matches a character defined by the same escape sequences used in string constants or the literal character c if \c is not an escape sequence.

              .            matches any character (including newline).

              ^            matches the front of a string.

              $            matches the back of a string.

              [c1c2c3...]  matches any character in the class c1c2c3... .  An interval of characters is denoted c1-c2 inside a class [...].

              [^c1c2c3...] matches any character not in the class c1c2c3...

       Regular expressions are built up from other regular expressions as follows:

              r1r2         matches r1 followed immediately by r2 (concatenation).

              r1 | r2      matches r1 or r2 (alternation).

              r*           matches r repeated zero or more times.

              r+           matches r repeated one or more times.

              r?           matches r zero or once.

              (r)          matches r, providing grouping.

       The increasing precedence of operators is alternation, concatenation and unary (*, + or ?).

       For example,

            /^[_a-zA-Z][_a-zA-Z0-9]*$/  and
            /^[-+]?([0-9]+\.?|\.[0-9])[0-9]*([eE][-+]?[0-9]+)?$/

       are matched by AWK identifiers and AWK numeric constants respectively.  Note that . has to be escaped to be recognized as a decimal point,  and  that  metacharacters
       are not special inside character classes.

       Any  expression can be used on the right hand side of the ~ or !~ operators or passed to a built-in that expects a regular expression.  If needed, it is converted to
       string, and then interpreted as a regular expression.  For example,

            BEGIN { identifier = "[_a-zA-Z][_a-zA-Z0-9]*" }

            $0 ~ "^" identifier

       prints all lines that start with an AWK identifier.

       mawk recognizes the empty regular expression, //, which matches the empty string and hence is matched by any string at the front, back and between  every  character.
       For example,

            echo  abc | mawk { gsub(//, "X") ; print }
            XaXbXcX

   4. Records and fields
       Records are read in one at a time, and stored in the field variable $0.  The record is split into fields which are stored in $1, $2, ..., $NF.  The built-in variable
       NF is set to the number of fields, and NR and FNR are incremented by 1.  Fields above $NF are set to "".

       Assignment to $0 causes the fields and NF to be recomputed.  Assignment to NF or to a field causes $0 to be reconstructed by concatenating the $i's separated by OFS.
       Assignment to a field with index greater than NF, increases NF and causes $0 to be reconstructed.

       Data input stored in fields is string, unless the entire field has numeric form and then the type is number and string.  For example,

            echo 24 24E |
            mawk '{ print($1>100, $1>"100", $2>100, $2>"100") }'
            0 1 1 1

       $0  and  $2  are string and $1 is number and string.  The first comparison is numeric, the second is string, the third is string (100 is converted to "100"), and the
       last is string.

   5. Expressions and operators
       The expression syntax is similar to C.  Primary expressions are numeric constants, string constants, variables, fields, arrays and function  calls.   The  identifier
       for  a  variable,  array  or function can be a sequence of letters, digits and underscores, that does not start with a digit.  Variables are not declared; they exist
       when first referenced and are initialized to null.

       New expressions are composed with the following operators in order of increasing precedence.

              assignment          =  +=  -=  *=  /=  %=  ^=
              conditional         ?  :
              logical or          ||
              logical and         &&
              array membership    in
              matching       ~   !~
              relational          <  >   <=  >=  ==  !=
              concatenation       (no explicit operator)
              add ops             +  -
              mul ops             *  /  %
              unary               +  -
              logical not         !
              exponentiation      ^
              inc and dec         ++ -- (both post and pre)
              field               $

       Assignment, conditional and exponentiation associate right to left; the other operators associate left to right.  Any expression can be parenthesized.

   6. Arrays
       Awk provides one-dimensional arrays.  Array elements are expressed as array[expr].  Expr is internally converted to string type, so, for example, A[1] and A["1"] are
       the  same  element  and  the  actual  index is "1".  Arrays indexed by strings are called associative arrays.  Initially an array is empty; elements exist when first
       accessed.  An expression, expr in array evaluates to 1 if array[expr] exists, else to 0.

       There is a form of the for statement that loops over each index of an array.

            for ( var in array ) statement

       sets var to each index of array and executes statement.  The order that var transverses the indices of array is not defined.

       The statement, delete array[expr], causes array[expr] not to exist.  mawk supports an extension, delete array, which deletes all elements of array.

       Multidimensional arrays are synthesized with concatenation using the built-in variable SUBSEP.  array[expr1,expr2] is equivalent to array[expr1 SUBSEP expr2].  Test‐
       ing for a multidimensional element uses a parenthesized index, such as

            if ( (i, j) in A )  print A[i, j]

   7. Builtin-variables
       The following variables are built-in and initialized before program execution.

              ARGC      number of command line arguments.

              ARGV      array of command line arguments, 0..ARGC-1.

              CONVFMT   format for internal conversion of numbers to string, initially = "%.6g".

              ENVIRON   array indexed by environment variables.  An environment string, var=value is stored as ENVIRON[var] = value.

              FILENAME  name of the current input file.

              FNR       current record number in FILENAME.

              FS        splits records into fields as a regular expression.

              NF        number of fields in the current record.

              NR        current record number in the total input stream.

              OFMT      format for printing numbers; initially = "%.6g".

              OFS       inserted between fields on output, initially = " ".

              ORS       terminates each record on output, initially = "\n".

              RLENGTH   length set by the last call to the built-in function, match().

              RS        input record separator, initially = "\n".

              RSTART    index set by the last call to match().

              SUBSEP    used to build multiple array subscripts, initially = "\034".

   8. Built-in functions
       String functions

              gsub(r,s,t)  gsub(r,s)
                     Global substitution, every match of regular expression r in variable t is replaced by string s.  The number of replacements is returned.  If t is omit‐
                     ted, $0 is used.  An & in the replacement string s is replaced by the matched substring of t.  \& and \\ put  literal & and  \,  respectively,  in  the
                     replacement string.

              index(s,t)
                     If t is a substring of s, then the position where t starts is returned, else 0 is returned.  The first character of s is in position 1.

              length(s)
                     Returns the length of string s.

              match(s,r)
                     Returns  the  index  of  the  first  longest match of regular expression r in string s.  Returns 0 if no match.  As a side effect, RSTART is set to the
                     return value.  RLENGTH is set to the length of the match or -1 if no match.  If the empty string is matched, RLENGTH is set to 0, and 1 is returned  if
                     the match is at the front, and length(s)+1 is returned if the match is at the back.

              split(s,A,r)  split(s,A)
                     String  s is split into fields by regular expression r and the fields are loaded into array A.  The number of fields is returned.  See section 11 below
                     for more detail.  If r is omitted, FS is used.

              sprintf(format,expr-list)
                     Returns a string constructed from expr-list according to format.  See the description of printf() below.

              sub(r,s,t)  sub(r,s)
                     Single substitution, same as gsub() except at most one substitution.

              substr(s,i,n)  substr(s,i)
                     Returns the substring of string s, starting at index i, of length n.  If n is omitted, the suffix of s, starting at i is returned.

              tolower(s)
                     Returns a copy of s with all upper case characters converted to lower case.

              toupper(s)
                     Returns a copy of s with all lower case characters converted to upper case.

       Arithmetic functions

              atan2(y,x)     Arctan of y/x between -pi and pi.

              cos(x)         Cosine function, x in radians.

              exp(x)         Exponential function.

              int(x)         Returns x truncated towards zero.

              log(x)         Natural logarithm.

              rand()         Returns a random number between zero and one.

              sin(x)         Sine function, x in radians.

              sqrt(x)        Returns square root of x.

              srand(expr)  srand()
                     Seeds the random number generator, using the clock if expr is omitted, and returns the value of the previous seed.  mawk seeds the random number gener‐
                     ator from the clock at startup so there is no real need to call srand().  Srand(expr) is useful for repeating pseudo random sequences.

   9. Input and output
       There are two output statements, print and printf.

              print  writes $0  ORS to standard output.

              print expr1, expr2, ..., exprn
                     writes expr1 OFS expr2 OFS ... exprn ORS to standard output.  Numeric expressions are converted to string with OFMT.

              printf format, expr-list
                     duplicates the printf C library function writing to standard output.  The complete ANSI C format specifications are recognized with conversions %c, %d,
                     %e, %E, %f, %g, %G, %i, %o, %s, %u, %x, %X and %%, and conversion qualifiers h and l.

       The argument list to print or printf can optionally be enclosed in parentheses.  Print formats numbers using OFMT or "%d" for exact integers.  "%c"  with  a  numeric
       argument  prints  the corresponding 8 bit character, with a string argument it prints the first character of the string.  The output of print and printf can be redi‐
       rected to a file or command by appending > file, >> file or | command to the end of the print statement.  Redirection opens file or  command  only  once,  subsequent
       redirections append to the already open stream.  By convention, mawk associates the filename "/dev/stderr" with stderr which allows print and printf to be redirected
       to stderr.  mawk also associates "-" and "/dev/stdout" with stdin and stdout which allows these streams to be passed to functions.

       The input function getline has the following variations.

              getline
                     reads into $0, updates the fields, NF, NR and FNR.

              getline < file
                     reads into $0 from file, updates the fields and NF.

              getline var
                     reads the next record into var, updates NR and FNR.

              getline var < file
                     reads the next record of file into var.

               command | getline
                     pipes a record from command into $0 and updates the fields and NF.

               command | getline var
                     pipes a record from command into var.

       Getline returns 0 on end-of-file, -1 on error, otherwise 1.

       Commands on the end of pipes are executed by /bin/sh.

       The function close(expr) closes the file or pipe associated with expr.  Close returns 0 if expr is an open file, the exit status if expr is a piped command,  and  -1
       otherwise.  Close is used to reread a file or command, make sure the other end of an output pipe is finished or conserve file resources.

       The  function fflush(expr) flushes the output file or pipe associated with expr.  Fflush returns 0 if expr is an open output stream else -1.  Fflush without an argu‐
       ment flushes stdout.  Fflush with an empty argument ("") flushes all open output.

       The function system(expr) uses /bin/sh to execute expr and returns the exit status of the command expr.  Changes made to the ENVIRON array are not passed to commands
       executed with system or pipes.

   10. User defined functions
       The syntax for a user defined function is

            function name( args ) { statements }

       The function body can contain a return statement

            return opt_expr

       A  return statement is not required.  Function calls may be nested or recursive.  Functions are passed expressions by value and arrays by reference.  Extra arguments
       serve as local variables and are initialized to null.  For example, csplit(s,A) puts each character of s into array A and returns the length of s.

            function csplit(s, A,    n, i)
            {
              n = length(s)
              for( i = 1 ; i <= n ; i++ ) A[i] = substr(s, i, 1)
              return n
            }

       Putting extra space between passed arguments and local variables is conventional.  Functions can be referenced before they are defined, but the function name and the
       '(' of the arguments must touch to avoid confusion with concatenation.

   11. Splitting strings, records and files
       Awk  programs  use  the  same  algorithm to split strings into arrays with split(), and records into fields on FS.  mawk uses essentially the same algorithm to split
       files into records on RS.

       Split(expr,A,sep) works as follows:

              (1)    If sep is omitted, it is replaced by FS.  Sep can be an expression or regular expression.  If it is an expression of non-string type, it  is  converted
                     to string.

              (2)    If  sep  = " " (a single space), then <SPACE> is trimmed from the front and back of expr, and sep becomes <SPACE>.  mawk defines <SPACE> as the regular
                     expression /[ \t\n]+/.  Otherwise sep is treated as a regular expression, except that meta-characters are ignored for  a  string  of  length  1,  e.g.,
                     split(x, A, "*") and split(x, A, /\*/) are the same.

              (3)    If expr is not string, it is converted to string.  If expr is then the empty string "", split() returns 0 and A is set empty.  Otherwise, all non-over‐
                     lapping, non-null and longest matches of sep in expr, separate expr into fields which are loaded into A.  The fields are placed  in  A[1],  A[2],  ...,
                     A[n]  and  split()  returns  n,  the number of fields which is the number of matches plus one.  Data placed in A that looks numeric is typed number and
                     string.

       Splitting records into fields works the same except the pieces are loaded into $1, $2,..., $NF.  If $0 is empty, NF is set to 0 and all $i to "".

       mawk splits files into records by the same algorithm, but with the slight difference that RS is really a terminator instead of a separator.  (ORS is really a  termi‐
       nator too).

              E.g.,  if  FS  =  ":+"  and $0 = "a::b:" , then NF = 3 and $1 = "a", $2 = "b" and $3 = "", but if "a::b:" is the contents of an input file and RS = ":+", then
              there are two records "a" and "b".

       RS = " " is not special.

       If FS = "", then mawk breaks the record into individual characters, and, similarly, split(s,A,"") places the individual characters of s into A.

   12. Multi-line records
       Since mawk interprets RS as a regular expression, multi-line records are easy.  Setting RS = "\n\n+", makes one or more blank lines separate records.  If FS  =  "  "
       (the default), then single newlines, by the rules for <SPACE> above, become space and single newlines are field separators.

              For  example, if a file is "a b\nc\n\n", RS = "\n\n+" and FS = " ", then there is one record "a b\nc" with three fields "a", "b" and "c".  Changing FS = "\n",
              gives two fields "a b" and "c"; changing FS = "", gives one field identical to the record.

       If you want lines with spaces or tabs to be considered blank, set RS = "\n([ \t]*\n)+".  For compatibility with other awks, setting RS = "" has the same effect as if
       blank lines are stripped from the front and back of files and then records are determined as if RS = "\n\n+".  Posix requires that "\n" always separates records when
       RS = "" regardless of the value of FS.  mawk does not support this convention, because defining "\n" as <SPACE> makes it unnecessary.

       Most of the time when you change RS for multi-line records, you will also want to change ORS to "\n\n" so the record spacing is preserved on output.

   13. Program execution
       This section describes the order of program execution.  First ARGC is set to the total number of command line arguments passed to the execution phase of the program.
       ARGV[0] is set the name of the AWK interpreter and ARGV[1] ...  ARGV[ARGC-1] holds the remaining command line arguments exclusive of options and program source.  For
       example with

            mawk  -f  prog  v=1  A  t=hello  B

       ARGC = 5 with ARGV[0] = "mawk", ARGV[1] = "v=1", ARGV[2] = "A", ARGV[3] = "t=hello" and ARGV[4] = "B".

       Next, each BEGIN block is executed in order.  If the program consists entirely of BEGIN blocks, then execution terminates, else an input stream is opened and  execu‐
       tion continues.  If ARGC equals 1, the input stream is set to stdin, else  the command line arguments ARGV[1] ...  ARGV[ARGC-1] are examined for a file argument.

       The  command  line  arguments  divide  into  three  sets: file arguments, assignment arguments and empty strings "".  An assignment has the form var=string.  When an
       ARGV[i] is examined as a possible file argument, if it is empty it is skipped; if it is an assignment argument, the assignment to var takes place and i skips to  the
       next  argument;  else ARGV[i] is opened for input.  If it fails to open, execution terminates with exit code 2.  If no command line argument is a file argument, then
       input comes from stdin.  Getline in a BEGIN action opens input.  "-" as a file argument denotes stdin.

       Once an input stream is open, each input record is tested against each pattern, and if it matches, the associated action is executed.  An expression pattern  matches
       if  it is boolean true (see the end of section 2).  A BEGIN pattern matches before any input has been read, and an END pattern matches after all input has been read.
       A range pattern, expr1,expr2 , matches every record between the match of expr1 and the match expr2 inclusively.

       When end of file occurs on the input stream, the remaining command line arguments are examined for a file argument, and if there is one it is opened,  else  the  END
       pattern is considered matched and all END actions are executed.

       In  the  example,  the assignment v=1 takes place after the BEGIN actions are executed, and the data placed in v is typed number and string.  Input is then read from
       file A.  On end of file A, t is set to the string "hello", and B is opened for input.  On end of file B, the END actions are executed.

       Program flow at the pattern {action} level can be changed with the

            next
            exit  opt_expr

       statements.  A next statement causes the next input record to be read and pattern testing to restart with the first pattern {action} pair in the  program.   An  exit
       statement  causes immediate execution of the END actions or program termination if there are none or if the exit occurs in an END action.  The opt_expr sets the exit
       value of the program unless overridden by a later exit or subsequent error.

EXAMPLES
       1. emulate cat.

            { print }

       2. emulate wc.

            { chars += length($0) + 1  # add one for the \n
              words += NF
            }

            END{ print NR, words, chars }

       3. count the number of unique "real words".

            BEGIN { FS = "[^A-Za-z]+" }

            { for(i = 1 ; i <= NF ; i++)  word[$i] = "" }

            END { delete word[""]
                  for ( i in word )  cnt++
                  print cnt
            }

       4. sum the second field of every record based on the first field.

            $1 ~ /credit|gain/ { sum += $2 }
            $1 ~ /debit|loss/  { sum -= $2 }

            END { print sum }

       5. sort a file, comparing as string

            { line[NR] = $0 "" }  # make sure of comparison type
                            # in case some lines look numeric

            END {  isort(line, NR)
              for(i = 1 ; i <= NR ; i++) print line[i]
            }

            #insertion sort of A[1..n]
            function isort( A, n,    i, j, hold)
            {
              for( i = 2 ; i <= n ; i++)
              {
                hold = A[j = i]
                while ( A[j-1] > hold )
                { j-- ; A[j+1] = A[j] }
                A[j] = hold
              }
              # sentinel A[0] = "" will be created if needed
            }

COMPATIBILITY ISSUES
       The Posix 1003.2(draft 11.3) definition of the AWK language is AWK as described in the AWK book with a few extensions that appeared in SystemVR4 nawk. The extensions
       are:

              New functions: toupper() and tolower().

              New variables: ENVIRON[] and CONVFMT.

              ANSI C conversion specifications for printf() and sprintf().

              New command options:  -v var=value, multiple -f options and implementation options as arguments to -W.

       Posix AWK is oriented to operate on files a line at a time.  RS can be changed from "\n" to another single character, but it is hard to find any use for this — there
       are no examples in the AWK book.  By convention, RS = "", makes one or more blank lines separate records, allowing multi-line records.  When RS = "", "\n" is  always
       a field separator regardless of the value in FS.

       mawk, on the other hand, allows RS to be a regular expression.  When "\n" appears in records, it is treated as space, and FS always determines fields.

       Removing the line at a time paradigm can make some programs simpler and can often improve performance.  For example, redoing example 3 from above,

            BEGIN { RS = "[^A-Za-z]+" }

            { word[ $0 ] = "" }

            END { delete  word[ "" ]
              for( i in word )  cnt++
              print cnt
            }

       counts the number of unique words by making each word a record.  On moderate size files, mawk executes twice as fast, because of the simplified inner loop.

       The following program replaces each comment by a single space in a C program file,

            BEGIN {
              RS = "/\*([^*]|\*+[^/*])*\*+/"
                 # comment is record separator
              ORS = " "
              getline  hold
              }

              { print hold ; hold = $0 }

              END { printf "%s" , hold }

       Buffering one record is needed to avoid terminating the last record with a space.

       With mawk, the following are all equivalent,

            x ~ /a\+b/    x ~ "a\+b"     x ~ "a\\+b"

       The  strings  get  scanned  twice, once as string and once as regular expression.  On the string scan, mawk ignores the escape on non-escape characters while the AWK
       book advocates \c be recognized as c which necessitates the double escaping of meta-characters in strings.  Posix explicitly declines to define  the  behavior  which
       passively forces programs that must run under a variety of awks to use the more portable but less readable, double escape.

       Posix  AWK  does  not recognize "/dev/std{out,err}" or \x hex escape sequences in strings.  Unlike ANSI C, mawk limits the number of digits that follows \x to two as
       the current implementation only supports 8 bit characters.  The built-in fflush first appeared in a recent (1993) AT&T awk released to netlib, and is not part of the
       posix standard.  Aggregate deletion with delete array is not part of the posix standard.

       Posix  explicitly leaves the behavior of FS = "" undefined, and mentions splitting the record into characters as a possible interpretation, but currently this use is
       not portable across implementations.

       Finally, here is how mawk handles exceptional cases not discussed in the AWK book or the Posix draft.  It is unsafe to assume consistency across  awks  and  safe  to
       skip to the next section.

              substr(s,  i,  n) returns the characters of s in the intersection of the closed interval [1, length(s)] and the half-open interval [i, i+n).  When this inter‐
              section is empty, the empty string is returned; so substr("ABC", 1, 0) = "" and substr("ABC", -4, 6) = "A".

              Every string, including the empty string, matches the empty string at the front so, s ~ // and s ~ "", are always 1 as is match(s, //) and match(s, "").   The
              last two set RLENGTH to 0.

              index(s, t) is always the same as match(s, t1) where t1 is the same as t with metacharacters escaped.  Hence consistency with match requires that index(s, "")
              always returns 1.  Also the condition, index(s,t) != 0 if and only t is a substring of s, requires index("","") = 1.

              If getline encounters end of file, getline var, leaves var unchanged.  Similarly, on entry to the END actions, $0, the fields and NF have  their  value  unal‐
              tered from the last record.

SEE ALSO
       egrep(1)

       Aho,  Kernighan  and  Weinberger,  The  AWK  Programming Language, Addison-Wesley Publishing, 1988, (the AWK book), defines the language, opening with a tutorial and
       advancing to many interesting programs that delve into issues of software design and analysis relevant to programming in any language.

       The GAWK Manual, The Free Software Foundation, 1991, is a tutorial and language reference that does not attempt the depth of the AWK book and assumes the reader  may
       be a novice programmer.  The section on AWK arrays is excellent.  It also discusses Posix requirements for AWK.

BUGS
       mawk cannot handle ascii NUL \0 in the source or data files.  You can output NUL using printf with %c, and any other 8 bit character is acceptable input.

       mawk  implements  printf()  and sprintf() using the C library functions, printf and sprintf, so full ANSI compatibility requires an ANSI C library.  In practice this
       means the h conversion qualifier may not be available.  Also mawk inherits any bugs or limitations of the library functions.

       Implementors of the AWK language have shown a consistent lack of imagination when naming their programs.

AUTHOR
       Mike Brennan (brennan@whidbey.com).

Version 1.2                                                                      Dec 22 1994                                                                         MAWK(1)

Linux常用命令

dd命令

ssh命令

tar命令

curl命令

top命令

tr命令

xargs命令

sort命令

du/df/free命令

。。。。待补充。。。。

shell 知识

function的使用

  1. shell的函数不能有参数列表
  2. 函数内部可以改变全局变量
a=10
function func1(){
	#echo "hello"
	#cd /home
	#touch a.txt
	a=3
}
func1
echo a   #应该输出3

这也是前两天面试官问我的问题,我还是没有答出来。。。。😅😅😅

其他内容,以后补充。。。。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/884463.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

阿里云函数计算 x NVIDIA 加速企业 AI 应用落地

作者&#xff1a;付宇轩 前言 阿里云函数计算&#xff08;Function Compute, FC&#xff09;是一种无服务器&#xff08;Serverless&#xff09;计算服务&#xff0c;允许用户在无需管理底层基础设施的情况下&#xff0c;直接运行代码。与传统的计算架构相比&#xff0c;函数…

【2023工业3D异常检测文献】PointCore: 基于局部-全局特征的高效无监督点云异常检测器

PointCore: Efficient Unsupervised Point Cloud Anomaly Detector Using Local-Global Features 1、Background 当前的点云异常检测器可以分为两类&#xff1a; &#xff08;1&#xff09;基于重建的方法&#xff0c;通过自动编码器重建输入点云数据&#xff0c;并通过比较原…

07-阿里云镜像仓库

07-阿里云镜像仓库 注册阿里云 先注册一个阿里云账号&#xff1a;https://www.aliyun.com/ 进入容器镜像服务控制台 工作台》容器》容器服务》容器镜像服务 实例列表》个人实例 仓库管理》镜像仓库》命名空间》创建命名空间 仓库管理》镜像仓库》镜像仓库》创建镜像仓库 使…

【AI】深度学习的数学--核心公式

1 梯度下降 f ( x Δ x , y Δ y ) ≃ f ( x , y ) ∂ f ( x , y ) ∂ x Δ x ∂ f ( x , y ) ∂ y Δ y f(x\Delta x,y\Delta y) \simeq f(x,y)\frac{\partial f(x,y)}{\partial x}\Delta x\frac{\partial f(x,y)}{\partial y}\Delta y f(xΔx,yΔy)≃f(x,y)∂x∂f(x,y)​…

MySQL 性能剖析全攻略

在使用 MySQL 数据库的过程中&#xff0c;性能问题往往是让开发者和管理员头疼的难题。为了有效地解决这些问题&#xff0c;我们需要对 MySQL 进行性能剖析。那么&#xff0c;如何在 MySQL 中进行性能剖析呢&#xff1f;本文将为你详细介绍。 一、为什么要进行性能剖析&#x…

基于安卓开发大型体育场管理系统的设计与实现(源码+定制+讲解)

博主介绍&#xff1a; ✌我是阿龙&#xff0c;一名专注于Java技术领域的程序员&#xff0c;全网拥有10W粉丝。作为CSDN特邀作者、博客专家、新星计划导师&#xff0c;我在计算机毕业设计开发方面积累了丰富的经验。同时&#xff0c;我也是掘金、华为云、阿里云、InfoQ等平台…

《开题报告》基于SpringBoot框架的高校专业实习管理系统开题报告的设计与实现源码++学习文档+答辩讲解视频

开题报告 研究背景 在当今高等教育日益普及与深化的背景下&#xff0c;高校专业实习作为学生将理论知识转化为实践能力、提前适应社会工作环境的重要环节&#xff0c;其重要性不言而喻。然而&#xff0c;传统的高校专业实习管理模式往往存在信息不对称、流程繁琐、效率低下、…

SSM+Vue共享单车管理系统

目录 1 项目介绍2 项目截图3 核心代码3.1 Controller3.2 Service3.3 Dao3.4 spring-mybatis.xml3.5 spring-mvc.xml3.5 Vue 4 数据库表设计5 文档参考6 计算机毕设选题推荐7 源码获取 1 项目介绍 博主个人介绍&#xff1a;CSDN认证博客专家&#xff0c;CSDN平台Java领域优质创作…

代码随想录_刷题记录_第四次

二叉树 — 理论基础 种类&#xff1a; 满二叉树&#xff08;所有层的节点都是满的&#xff0c;k&#xff1a;深度 节点数量&#xff1a;2^k - 1&#xff09;完全二叉树&#xff08;除了最后一层&#xff0c;其余层全满&#xff0c;并且最后一层从左到右连续&#xff09;二叉搜…

信道衰落的公式

对于天线&#xff1a; 对于天线的面积计算&#xff1a; 天线的接收功率密度&#xff1a; 天线的接收功率&#xff1a; 移动无线信道&#xff08;I&#xff09; (xidian.edu.cn)https://web.xidian.edu.cn/zma/files/20150710_153736.pdf 更加常用的考虑了额外的信道衰落pathlo…

2024 maya的散布工具sppaint3d使用指南

目前工具其实可以分为三个版本 1 最老的原版 时间还是2011年的&#xff0c;只支持python2版的maya 2 作者python3更新版 后来作者看maya直到2022上还是没有类似好用方便的工具&#xff0c;于是更新到了2022版本 这个是原作者更新的2022版本&#xff0c;改成了python3&#…

敏感字段加密 - 华为OD统一考试(E卷)

2024华为OD机试(E卷+D卷+C卷)最新题库【超值优惠】Java/Python/C++合集 题目描述 【敏感字段加密】给定一个由多个命令字组成的命令字符串: 1、字符串长度小于等于127字节,只包含大小写字母,数字,下划线和偶数个双引号; 2、命令字之间以一个或多个下划线 进行分割; 3、可…

Study-Oracle-10-ORALCE19C-RAC集群搭建(一)

一、硬件信息及配套软件 1、硬件设置 RAC集群虚拟机:CPU:2C、内存:10G、操作系统:50G Openfile数据存储:200G (10G*2) 2、网络设置 主机名公有地址私有地址VIP共享存储(SAN)rac1192.168.49.13110.10.10.20192.168.49.141192.168.49.130rac2192.168.49.13210.10.10.3…

单体到微服务架构服务演化过程

架构服务化 聊聊从单体到微服务架构服务演化过程 单体分层架构 在 Web 应用程序发展的早期&#xff0c;大部分工程是将所有的服务端功能模块打包到单个巨石型&#xff08;Monolith&#xff09;应用中&#xff0c;譬如很多企业的 Java 应用程序打包为 war 包&#xff0c;最终会形…

JSP(Java Server Pages)基础使用二

简单练习在jsp页面上输出出乘法口诀表 既然大家都是来看这种代码的人了&#xff0c;那么这种输出乘法口诀表的这种简单算法肯定是难不住大家了&#xff0c;所以这次主要是来说jsp的使用格式问题。 <%--Created by IntelliJ IDEA.User: ***Date: 2024/7/18Time: 11:26To ch…

线性表二——栈stack

第一题 #include<bits/stdc.h> using namespace std; stack<char> s; int n; string ced;//如何匹配 出现的右括号转换成同类型的左括号&#xff0c;方便我们直接和栈顶元素 char cheak(char c){if(c)) return (;if(c]) return [;if(c}) return {;return \0;/…

css边框修饰

一、设置线条样式 通过 border-style 属性设置&#xff0c;可选择的一些属性如下&#xff1a; dotted&#xff1a;点线 dashed&#xff1a;虚线 solid&#xff1a;实线 double&#xff1a;双实线 效果如下&#xff1a; 二、设置边框线宽度 ① 通过 border-width 整体设置…

【深度学习】深度卷积神经网络(AlexNet)

在 LeNet 提出后&#xff0c;卷积神经网络在计算机视觉和机器学习领域中很有名气&#xff0c;但并未起到主导作用。 这是因为 LeNet 在更大、更真实的数据集上训练的性能和可行性还有待研究。 事实上&#xff0c;在 20 世纪 90 年代到 2012 年之间的大部分时间里&#xff0c;…

时间技能物品竞品抢拍拍卖发布h5公众号小程序开源版开发

时间技能物品竞品抢拍拍卖发布h5公众号小程序开源版开发 利用新型营销方式&#xff0c;将闲置的物品通过拍卖&#xff0c;让价格一提再提让用户趣在其中&#xff0c;营造一种不一样的购物体验! 拍卖列表页 列表页采用多分类&#xff0c;广告轮播及流动公告和拍卖商品列表组成…

神经网络(二):卷积神经网络

文章目录 一、图像的本质1.1单通道图像&#xff1a;灰度图1.2多通道图像 二、卷积神经网络2.1基本结构2.2卷积层2.2.1卷积操作2.2.2填充padding2.2.3步幅strides2.2.4多通道图像卷积&#xff1a;单卷积核2.2.5多通道图像卷积&#xff1a;多卷积核2.2.5卷积层的参数与激活函数 2…