zoukankan      html  css  js  c++  java
  • Linux中 tr 命令详解

     tr - translate or delete characters 主要用于转换和删除字符

    带有最常用选项的t r命令格式为:
    tr -c -d -s [ "string1_to_translate_from" ] [ "string2_to_translate_to" ] input_file
    -c 用字符串1中字符集的补集替换此字符集,要求字符集为ASCII。
    -d 删除字符串1中所有输入字符。
    -s 删除所有重复出现字符序列,只保留第一个;即将重复出现字符串压缩为一个字符串。
    Input-file是转换文件名。虽然可以使用其他格式输入,但这种格式最常用。

    字符范围
    使用tr时,可以指定字符串列表或范围作为形成字符串的模式。这看起来很像正则表达式,但实际上不是。指定字符串1或字符串2的内容时,只能使用单字符或字符串范围或列表。
    [a-z]    a-z内的字符组成的字符串
    [A-Z]    A-Z内的字符组成的字符串
    [0-9]    数字串
    /octal   一个三位的八进制数,对应有效的ASCII字符
    [O*n]    表示字符O重复出现指定次数n 如:[O*2]匹配OO的字符串。
    大部分tr变种支持字符类和速记控制字符。
    字符类格式为[:class],包含数字、希腊字母、空行、小写、大写、ctrl键、空格、点记符、图形等等。

    去除重复出现的字符 -s  因为都是字母,故使用[a-z]

    [python@master2 tr]$ more a.txt 
    helloo worldddd
    [python@master2 tr]$ cat a.txt |tr -s "[a-z]"
    helo world
    [python@master2 tr]$ tr -s "[a-z]" < a.txt 
    helo world


    删除空行

    要删除空行,可将之剔出文件。使用-s来做这项工作。换行的八进制表示为12

    [python@master2 tr]$ more b.txt 
    this is a one line
    
    two
    
    thress
    
    
    foure
    [python@master2 tr]$ 
    [python@master2 tr]$ 
    [python@master2 tr]$ tr -s "[12]"< b.txt 
    this is a one line
    two
    thress
    foure
    [python@master2 tr]$ tr -s "[
    ]" < b.txt 
    this is a one line
    two
    thress
    foure

    大写到小写 
    除了删除控制字符,转换大小写是tr最常用的功能。为此需指定即将转换的小写字符[a-z]和转换结果[A-Z]。 
    第一个例子,tr从一个包含大小写字母的字符串中接受输入。

    [python@master2 tr]$ echo "May Day,May Day,Going Down.." | tr "[a-z]" "[A-Z]" 
    MAY DAY,MAY DAY,GOING DOWN..
    [python@master2 tr]$ 
    [python@master2 tr]$ 
    [python@master2 tr]$ echo "May Day,May Day,Going Down.." | tr "[A-Z]" "[a-z]" 
    may day,may day,going down..
    [python@master2 tr]$  echo "Hello World I Love You" |tr [:lower:] [:upper:]
    HELLO WORLD I LOVE YOU

    删除指定字符  #-d代表删除,[0-9]代表所有的数字,[: ]代表冒号和空格

    [python@master2 tr]$ more c.txt 
    Monday     09:00
    Tuesday    09:10
    Wednesday  10:11
    Thursday   11:30
    Friday     08:00
    Saturday   07:40
    Sunday     10:00
    [python@master2 tr]$ cat c.txt |tr -d "[0-9][:]"
    Monday     
    Tuesday    
    Wednesday  
    Thursday   
    Friday     
    Saturday   
    Sunday   
  • 相关阅读:
    [POJ 1200]Crazy Search
    [来源不详]删数方案数
    noip搜索模拟题 骰子
    [SDOI2010]地精部落
    [HAOI2008]硬币购物
    BZOJ1009: [HNOI2008]GT考试
    BZOJ1830: [AHOI2008]Y型项链 & BZOJ1789: [Ahoi2008]Necklace Y型项链
    BZOJ1251: 序列终结者
    BZOJ3620: 似乎在梦中见过的样子
    BZOJ4477: [Jsoi2015]字符串树
  • 原文地址:https://www.cnblogs.com/hello-wei/p/10365215.html
Copyright © 2011-2022 走看看