zoukankan      html  css  js  c++  java
  • Shell教程 之字符串

    1.Shell字符串

    字符串是shell编程中最常用最有用的数据类型(除了数字和字符串,也没啥其它类型好用了),字符串可以用单引号,也可以用双引号,也可以不用引号。

    1.1 单引号

    str='I am uniquefu'
    

     单引号字符串的限制:

    • 单引号里的任何字符都会原样输出,单引号字符串中的变量是无效的;
    • 单引号字串中不能出现单独一个的单引号(对单引号使用转义符后也不行),但可成对出现,作为字符串拼接使用

    1.2 双引号

    name="http://www.cnblogs.com/uniquefu"
    str="Hello, I know you are "$name"! 
    "
    
    echo ${str}

    输出结果:

    [root@test3101-3 bin]# ./test.sh 
    Hello, I know you are "http://www.cnblogs.com/uniquefu"! 
    
    

    双引号的优点:

    • 双引号里可以有变量
    • 双引号里可以出现转义字符

    1.3 拼接字符串

    your_name="uniquefu"
    # 使用双引号拼接
    greeting="hello, "$your_name" !"
    greeting_1="hello, ${your_name} !"
    echo $greeting  $greeting_1
    # 使用单引号拼接
    greeting_2='hello, '$your_name' !'
    greeting_3='hello, ${your_name} !'
    echo $greeting_2  $greeting_3

    运行结果

    [root@test3101-3 bin]# ./test.sh  
    hello, uniquefu ! hello, uniquefu !
    hello, uniquefu ! hello, ${your_name} !
    

    1.4 获取字符串长度

    your_name="uniquefu"
    echo ${#your_name}

    输出结果:

    [root@test3101-3 bin]# ./test.sh  
    8
    

    1.5 提取子字符串

    以下实例从字符串第 3 个字符开始截取 5 个字符

    your_name="uniquefu"
    echo ${your_name:2:5}

    输出结果:

    [root@test3101-3 bin]# ./test.sh  
    iquef
    

    1.6 查找字符串  

    查找字符 i 或 f 的位置(哪个字母先出现就计算哪个):

    your_name="uniquefu"
    echo `expr index "$your_name" if`  # 输出 3
    

     注意: 以上脚本中 ` 是反引号,而不是单引号 ',不要看错了哦 

  • 相关阅读:
    python解析网页
    node.js 爬虫
    c++ split实现
    foldl foldr
    爬虫http header gzip
    命令[10]
    命令[08]
    命令[15]
    命令[13]
    命令[11]
  • 原文地址:https://www.cnblogs.com/uniquefu/p/9552885.html
Copyright © 2011-2022 走看看