pandasql: Make python speak SQL



One of my favorite things about Python is that users get the benefit of observing the R community and then emulating the best parts of it. I’m a big believer that a language is only as helpful as its libraries and tools.

This post is about pandasql, a Python package we (Yhat) wrote that emulates the R package sqldf. It’s a small but mighty library comprised of just 358 lines of code. The idea of pandasql is to make Python speak SQL. For those of you who come from a SQL-first background or still “think in SQL”, pandasql is a nice way to take advantage of the strengths of both languages.

In this introduction, we’ll show you to get up and running with pandasql inside of Rodeo, the integrated development environment (IDE) we built for data exploration and analysis. Rodeo is an open source and completely free tool. If you’re an R user, its a comparable tool with a similar feel to RStudio. As of today, Rodeo can only run Python code, but last week we added syntax highlighting for a bunch of other languages to the editor (markdown, JSON, julia, SQL, markdown). As you may have read or guessed, we’ve got big plans for Rodeo, including adding SQL support so that you can run your SQL queries right inside of Rodeo, even without our handy little pandasql. More on that in the next week or two!

Downloading Rodeo

Start by downloading Rodeo for Mac, Windows or Linux from the Rodeo page on the Yhat website.

ps If you download Rodeo and encounter a problem or simply have a question, we monitor our discourse forum 24/7 (okay, almost).

A bit of background, if you’re curious

Behind the scenes, pandasql uses the module to transfer data between DataFrame and SQLite databases. Operations are performed in SQL, the results returned, and the database is then torn down. The library makes heavy use of pandas write_frame and frame_query, two functions which let you read and write to/from pandas and (most) any SQL database.

Install pandasql

Install pandasql using the package manager pane in Rodeo. Simply search for pandasql and click Install Package.

You can also run ! pip install pandasql from the text editor if you prefer to install that way.

Check out the datasets

pandasql has two built-in datasets which we’ll use for the examples below.

  • meat: Dataset from the U.S. Dept. of Agriculture containing metrics on livestock, dairy, and poultry outlook and production
  • births: Dataset from the United Nations Statistics Division containing demographic statistics on live births by month

Run the following code to check out the data sets.

<code>#Checking out meat and birth data
from pandasql import sqldf
from pandasql import load_meat, load_births

meat = load_meat()
births = load_births()

#You can inspect the dataframes directly if you're using Rodeo
#These print statements are here just in case you want to check out your data in the editor, too
print meat.head()
print births.head()

Inside Rodeo, you really don’t even need the print.variable.head() statements, since you can actually just examine the dataframes directly.

An odd graph

<code># Let's make a graph to visualize the data
# Bet you haven't had a title quite like this before
import matplotlib.pyplot as plt
from pandasql import *
import pandas as pd

pysqldf = lambda q: sqldf(q, globals())

q  = """
  , m.beef
  , b.births
  meat m
  births b
    ON =
WHERE &gt; '1974-12-31';

meat = load_meat()
births = load_births()

df = pysqldf(q)
df.births = df.births.fillna(method='backfill')

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(pd.rolling_mean(df['beef'], 12), color='b')
ax1.set_xlabel('months since 1975')
ax1.set_ylabel('cattle slaughtered', color='b')

ax2 = ax1.twinx()
ax2.plot(pd.rolling_mean(df['births'], 12), color='r')
ax2.set_ylabel('babies born', color='r')
plt.title("Beef Consumption and the Birth Rate")

Notice that the plot appears both in the console and the plot tab (bottom right tab).

Tip: You can “pop out” your plot by clicking the arrows at the top of the pane. This is handy if you’re working on multiple monitors and want to dedicate one just to your data visualzations.


To keep this post concise and easy to read, we’ve just given the code snippets and a few lines of results for most of the queries below.

If you’re following along in Rodeo, a few tips as you’re getting started:

  • Run Script will indeed run everything you have written in the text editor
  • You can highlight a code chunk and run it by clicking Run Line or pressing Command + Enter
  • You can resize the panes (when I’m not making plots I shrink down the bottom right pane)


Write some SQL and execute it against your pandas DataFrame by substituting DataFrames for tables.

<code>q = """
    LIMIT 10;"""

print sqldf(q, locals())

#                   date  beef  veal  pork  lamb_and_mutton broilers other_chicken turkey
# 0  1944-01-01 00:00:00   751    85  1280               89     None          None   None
# 1  1944-02-01 00:00:00   713    77  1169               72     None          None   None
# 2  1944-03-01 00:00:00   741    90  1128               75     None          None   None
# 3  1944-04-01 00:00:00   650    89   978               66     None          None   None

pandasql creates a DB, schema and all, loads your data, and runs your SQL.


pandasql supports aggregation. You can use aliased column names or column numbers in your group byclause.

<code># births per year
q = """
        strftime("%Y", date)
        , SUM(births)
    FROM births
    GROUP BY 1
    ORDER BY 1;

print sqldf(q, locals())

#    strftime("%Y", date)  SUM(births)
# 0                  1975      3136965
# 1                  1976      6304156
# 2                  1979      3333279
# 3                  1982      3612258

locals() vs. globals()

pandasql needs to have access to other variables in your session/environment. You can pass locals() to pandasql when executing a SQL statement, but if you’re running a lot of queries that might be a pain. To avoid passing locals all the time, you can add this helper function to your script to set globals() like so:

<code>def pysqldf(q):
    return sqldf(q, globals())

q = """
    LIMIT 10;"""

print pysqldf(q)
# 0  1975-01-01 00:00:00  265775
# 1  1975-02-01 00:00:00  241045
# 2  1975-03-01 00:00:00  268849


You can join dataframes using normal SQL syntax.

<code># joining meats + births on date
q = """
        , b.births
        , m.beef
        meat m
        births b
            on =
    LIMIT 100;

joined = pysqldf(q)
print joined.head()
#date  births    beef
#0  1975-01-01 00:00:00.000000  265775  2106.0
#1  1975-02-01 00:00:00.000000  241045  1845.0
#2  1975-03-01 00:00:00.000000  268849  1891.0

WHERE conditions

Here’s a WHERE clause.

<code>q = """
        , beef
        , veal
        , pork
        , lamb_and_mutton
        lamb_and_mutton &gt;= veal
    ORDER BY date DESC
    LIMIT 10;

print pysqldf(q)
#                   date    beef  veal    pork  lamb_and_mutton
# 0  2012-11-01 00:00:00  2206.6  10.1  2078.7             12.4
# 1  2012-10-01 00:00:00  2343.7  10.3  2210.4             14.2
# 2  2012-09-01 00:00:00  2016.0   8.8  1911.0             12.5
# 3  2012-08-01 00:00:00  2367.5  10.1  1997.9             14.2

It’s just SQL

Since pandasql is powered by SQLite3, you can do most anything you can do in SQL. Here are some examples using common SQL features such as subqueries, order by, functions, and unions.

# e.g. `RANDOM()`
q = """SELECT
    LIMIT 10;"""
print pysqldf(q)
#                   date  beef  veal  pork  lamb_and_mutton  broilers other_chicken  turkey
# 0  1967-03-01 00:00:00  1693    65  1136               61     472.0          None    26.5
# 1  1944-12-01 00:00:00   764   146  1013               91       NaN          None     NaN
# 2  1969-06-01 00:00:00  1666    50   964               42     573.9          None    85.4
# 3  1983-03-01 00:00:00  1892    37  1303               36    1106.2          None   182.7

q = """
            , 'beef' AS meat_type
            , beef AS value
        FROM meat
        UNION ALL
            , 'veal' AS meat_type
            , veal AS value
        FROM meat

        UNION ALL

            , 'pork' AS meat_type
            , pork AS value
        FROM meat
        UNION ALL
            , 'lamb_and_mutton' AS meat_type
            , lamb_and_mutton AS value
        FROM meat
        ORDER BY 1
print pysqldf(q).head(20)
#                    date        meat_type  value
# 0   1944-01-01 00:00:00             beef    751
# 1   1944-01-01 00:00:00             veal     85
# 2   1944-01-01 00:00:00             pork   1280
# 3   1944-01-01 00:00:00  lamb_and_mutton     89

# subqueries
# fancy!
q = """
        , m1.beef
        meat m1
        FROM meat
            beef &gt;= broilers
        ORDER BY date)

more_beef_than_broilers = pysqldf(q)
print more_beef_than_broilers.head(10)
#                   date  beef
# 0  1960-01-01 00:00:00  1196
# 1  1960-02-01 00:00:00  1089
# 2  1960-03-01 00:00:00  1201
# 3  1960-04-01 00:00:00  1066

Final thoughts

pandas is an incredible tool for data analysis in large part, we think, because it is extremely digestible, succinct, and expressive. Ultimately, there are tons of reasons to learn the nuances of mergejoinconcatenatemelt and other native pandas features for slicing and dicing data. Check out the docs for some examples.

Our hope is that pandasql will be a helpful learning tool for folks new to Python and pandas. In my own personal experience learning R, sqldf was a familiar interface helping me become highly productive with a new tool as quickly as possible.




得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd()








返回一个路径的目录名和文件名:os.path.split()     eg os.path.split(‘/home/swaroop/byte/code/poem.txt’) 结果:(‘/home/swaroop/byte/code’, ‘poem.txt’)




运行shell命令: os.system()

读取和设置环境变量:os.getenv() 与os.putenv()

给出当前平台使用的行终止符:os.linesep    Windows使用’\r\n’,Linux使用’\n’而Mac使用’\r’

指示你正在使用的平台       对于Windows,它是’nt’,而对于Linux/Unix用户,它是’posix’

重命名:os.rename(old, new)






os.mknod(“test.txt”)        创建空文件
fp = open(“test.txt”,w)     直接打开一个文件,如果文件不存在则创建文件

关于open 模式:

w     以写方式打开,
a     以追加模式打开 (从 EOF 开始, 必要时创建新文件)
r+     以读写模式打开
w+     以读写模式打开 (参见 w )
a+     以读写模式打开 (参见 a )
rb     以二进制读模式打开
wb     以二进制写模式打开 (参见 w )
ab     以二进制追加模式打开 (参见 a )
rb+    以二进制读写模式打开 (参见 r+ )
wb+    以二进制读写模式打开 (参见 w+ )
ab+    以二进制读写模式打开 (参见 a+ )[size])                     #size为读取的长度,以byte为单位

fp.readline([size])                 #读一行,如果定义了size,有可能返回的只是一行的一部分

fp.readlines([size])                #把文件每一行作为一个list的一个成员,并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数,size是表示读取内容的总长,也就是说可能只读到文件的一部分。

fp.write(str)                      #把str写到文件中,write()并不会在str后加上一个换行符

fp.writelines(seq)            #把seq的内容全部写到文件中(多行一次性写入)。这个函数也只是忠实地写入,不会在每行后面加上任何东西。

fp.close()                        #关闭文件。python会在一个文件不用后自动关闭文件,不过这一功能没有保证,最好还是养成自己关闭的习惯。  如果一个文件在关闭后还对其进行操作会产生ValueError

fp.flush()                                      #把缓冲区的内容写入硬盘

fp.fileno()                                      #返回一个长整型的”文件标签“

fp.isatty()                                      #文件是否是一个终端设备文件(unix系统中的)

fp.tell()                                         #返回文件操作标记的当前位置,以文件的开头为原点                                       #返回下一行,并将文件操作标记位移到下一行。把一个file用于for … in file这样的语句时,就是调用next()函数来实现遍历的。[,whence])              #将文件打操作标记移到offset的位置。这个offset一般是相对于文件的开头来计算的,一般为正数。但如果提供了whence参数就不一定了,whence可以为0表示从头开始计算,1表示以当前位置为原点计算。2表示以文件末尾为原点进行计算。需要注意,如果文件以a或a+的模式打开,每次进行写操作时,文件操作标记会自动返回到文件末尾。

fp.truncate([size])                       #把文件裁成规定的大小,默认的是裁到当前文件操作标记的位置。如果size比文件的大小还要大,依据系统的不同可能是不改变文件,也可能是用0把文件补到相应的大小,也可能是以一些随机的内容加上去。


os.mkdir(“file”)                   创建目录
shutil.copyfile(“oldfile”,”newfile”)       oldfile和newfile都只能是文件
shutil.copy(“oldfile”,”newfile”)            oldfile只能是文件夹,newfile可以是文件,也可以是目标目录
shutil.copytree(“olddir”,”newdir”)        olddir和newdir都只能是目录,且newdir必须不存在
os.rename(“oldname”,”newname”)       文件或目录都是使用这条命令
shutil.rmtree(“dir”)    空目录、有内容的目录都可以删
os.chdir(“path”)   换路径



 1 将文件夹下所有图片名称加上’_fc’


# -*- coding:utf-8 -*-
import re
import os
import time
#’连接符’.join(list) 将列表组成字符串
def change_name(path):
global i
if not os.path.isdir(path) and not os.path.isfile(path):
return False
if os.path.isfile(path):
file_path = os.path.split(path) #分割出目录与文件
lists = file_path[1].split(‘.’) #分割出文件与文件扩展名
file_ext = lists[-1] #取出后缀名(列表切片操作)
img_ext = [‘bmp’,’jpeg’,’gif’,’psd’,’png’,’jpg’]
if file_ext in img_ext:
i+=1 #注意这里的i是一个陷阱
#img_ext = ‘bmp|jpeg|gif|psd|png|jpg’
#if file_ext in img_ext:
#    print(‘ok—‘+file_ext)
elif os.path.isdir(path):
for x in os.listdir(path):
change_name(os.path.join(path,x)) #os.path.join()在路径处理上很有用
img_dir = ‘D:\\xx\\xx\\images’
img_dir = img_dir.replace(‘\\’,’/’)
start = time.time()
i = 0
c = time.time() – start
print(‘总共处理了 %s 张图片’%(i))


总共处理了 109 张图片






1.Visual Studio

  1. Visual Studio Productivity Power tool:Visual Studio专业版(及以上)的扩展,具有丰富的功能,如快速查找,导航解决方案,可搜索的附加参考对话框等
  2. ReSharper:提高.NET开发人员生产力的工具,提高代码质量,通过提供快速修复消除错误,等等
  3. MZ-Tools:它可以在方法、文件、项目、解决方案或项目组、选定的文本,文件组合或项目组合中找到字符串。结果示于下面的结果窗口中,比由Microsoft IDE提供的要更方便。
  4. Web Essentials:提高生产力和帮助高效编写CSS,JavaScript,HTML等
  5. MSVSMON:远程调试监视器(msvsmon.exe)是一个Visual Studio连接进行远程调试的小型应用程序。在远程调试时,Visual Studio运行在一台计算机(调试器主机)上,远程调试监视器运行与你正在调试的应用程序运行在一台远程计算机上。
  6. WIX toolset:从XML源代码构建Windows安装程序包。
  7. Code digger::Code Digger是Visual Studio 2012/2013扩展程序,它可以帮助你了解你的代码行为。
  8. CodeMaid:CodeMaid是一个开源的Visual Studio 2012/2013/2015扩展程序,用于清理,挖掘和简化你的代码。
  9. OzCode:强大的Visual Studio调试器可视化工具。
  10. CodeRush:这是一个Visual Studio的重构和生产率插件。
  11. T4 Text Template::在Visual Studio中,T4 Text Template用作生成代码文件的模板。模板可以通过编写文本块和控制逻辑来定义。
  12. Indent Guides:在每个缩进级别添加垂直线。
  13. PowerShell Tools:一套用于开发和调试PowerShell脚本以及Visual Studio 2015中模块的工具。
  14. Visual Studio Code:免费的跨平台编辑器,用来构建和调试现代web和云的应用程序。 [由Cheung Tat Ming提供]
  15. AutoPoco:AutoPoco是一个高度可配置的框架,用于流畅构建可读的来自于Plain Old CLRObjects的测试数据。
  16. Supercharger:这是一个旨在显著改善Visual Studio开发体验的扩展程序。它建立在并增强了先前的VS10x产品,如CodeMAP、Editor View Enhancer、Comments Extender,同时还增加了新的高品质工具。


  1. Fiddler:捕捉HTTP请求/响应以及模拟请求行为。
  2. AutoMapper:对象到对象的映射。例如,该工具可用于映射实体对象到领域对象,而不是写手动映射代码。
  3. Unity/Ninject/Castle Windsor/StructureMap/Spring.Net:依赖注入框架。有很多可用的DI框架。
  4. .NET Reflector:.NET程序集反编译器。
  5. dotPeek:.NET程序集反编译器。
  6. ILSpy::.NET程序集反编译器。
  7. memprofiler:查找内存泄漏并优化内存使用的强大工具。
  8. PostSharp:删除重复编码,并防止由于横切关注点以及面向方面编程而造成的代码膨胀。
  9. ASPhere:有GUI的web.config编辑器。


  1. Swagger UI:API测试和文档工具。[视频]
  2. PostMan:REST客户端Chrom扩展程序。 [由 Cheung Tat Ming提供]


  1. SOAP UI:API测试工具,支持所有标准协议和技术。
  2. WireShark:这是一个针对Unix和Windows的网络协议分析仪。它可以在TCP层捕获流量,帮助你发现soap封套。
  3. Svc TraceViewer:可以更好地查看由WCF产出的巨大跟踪文件。
  4. Svc Config Editor:用于管理WCF相关配置的GUI工具。


  1. QueueExplorer 3.4:复制,移动或删除邮件,保存和加载,压力测试,查看和编辑完整的邮件主体(通过.NET序列化对象的特殊支持),以及更多可对MSMQ做的。


  1. LINQ Pad?:LINQPad是一个轻量级的工具,用于测试对SQL Server数据库的LINQ查询。它也可以测试用不同的.NET语言,如C#,VB等写的代码片断。
  2. LINQ Insight:LINQ Insight Express是一个Visual Studio插件,它允许你在设计时分析你的LINQ查询,并简化了编写和调试LINQ查询。


  1. RegEx tester:用于正则表达式测试的Visual Studio扩展程序。
  2. regexr:在线RegEx开发和测试工具。
  3. regexpal:在线RegEx开发和测试工具。
  4. Expresso:Expresso是一个用于RegEx开发和测试的桌面工具。
  5. RegexMagic :用于自动生成来自于文本模式的正则表达式的工具。用户需要通过标记字串和选择不同的选项来培养模式。在此基础上,将自动生成正则表达式。这些工具还可以生成不同语言所需的代码。 [由: Samuel Christison提供]

8.Javascript / JQuery/ AngularJS

  1. JSHint:JavaScript代码质量的工具。还有一个工具,JSLine,它执行更严格的规则。
  2. JSFiddle:提供在浏览器中的一个环境,用来测试HTML,CSS和Javascript / JQuery。
  3. Protractor:端到端的框架用来测试angular应用程序。
  4. Batarang:添加工具用于调试和分析AngularJS应用程序。


  1. SQL Profiler:SQL跟踪用来监测数据库引擎实例。
  2. ExpressProfiler:ExpressProfiler(又名SqlExpress Profiler)是有着基本GUI和集成的SQL Server Profiler简单又快捷的替代品。这可以与Express 和SQL Server 2005/2008 / 2008R2 / 2012/2014的non-Express 版本一起使用。 [由RickZeeland提供]
  3. SQL Sentry Plan explorer:工具提供SQL查询执行计划更好的图形视图。
  4. SQL Complete:提供SQL Server Management Studio和Visual Studio智能感知功能和改进的SQL格式器。
  5. NimbleText:文本操作和代码生成工具。
  6. Query Express:轻量级SQL查询分析器。
  7. IO Meter:提供IO子系统的细节。
  8. sqldecryptor:破译SQL Server对象,如存储过程,函数,触发器,视图,通过加密选项加密。
  9. SpatialViewer:查看和创建空间数据。
  10. ClearTrace:导入跟踪和探查文件到SQL Server并显示汇总性能信息。
  11. Internals Viewer for SQL Server:Internals Viewer是一个查看SQL Server存储引擎,查阅数据如何物理分配,组织和存储的工具。
  12. PAL:在性能日志读取,使用已知阈值分析。
  13. sqlquerystress:用T-SQL查询和程序的性能压力测试助攻。


  1. NHibernate Mapping Generator:生成NHibernate映射文件和对应于现有DB表的实体类。


  1. Tally ERP 9
  2. Tally dll:.NET的一个动态链接库,用于集成Tally Accounting软件以便于用编程的方式push和pull数据。


  1. StyleCop:StyleCop是静态的代码分析工具,它强制你的C#源代码执行配置风格和一致性规则设置。它可以从Visual Studio内部运行或集成到MSBuild项目。
  2. FxCop?:FxCop是一个静态代码分析工具,它通过分析.NET程序集强制开发标准。


  1. WireShark:这是一个用于Unix和Windows的网络协议分析仪。它可以捕获TCP层的流量。
  2. HTTP Monitor:使开发人员可以查看你的计算机和互联网之间的所有HTTP流量。这包括请求数据(例如HTTP响应头和表单GET和POST数据)和响应数据(包括HTTP响应头和正文)。


  1. Glimpse:提供服务器端诊断数据。如,对于ASP.NET MVC项目,你需要从NuGet添加它。Glimpse的数据可以告诉你不同层面的延迟,真正表明你可以优化代码/解决方案以提高性能的区域。


  1. PerfMon:使用性能计数器监控系统性能。
  2. yslow:YSlow分析web页面,并基于Yahoo!高性能网站的规则指出它们为什么这么缓慢。


  1. Telerik Code Converter:C#到VB以及VB到C#的代码转换器。这是一个在线编辑器。但是你可以选择“批量转换”以及zip格式上传文件。


  1. FileHelpers:.NET库,导入/导出文件、字符串或流中固定长度或有分隔记录的数据。
  2. LogParser:你可以写SQL到查询来应对各种日志文件,以及导出数据到各种目的地,如SQL表、CSV文件。


  1. Wink:演示文稿制作软件。使用Wink,你可以捕捉截图,添加说明,注释等,以及创建演示。


  1. Notepad++:源代码编辑器。
  2. Notepad2:轻量级又功能丰富的记事本般的文本编辑器。
  3. sublimetext:一个功能丰富的文本编辑器。


  1. GhostDoc:GhostDoc是一个Visual Studio扩展程序,自动生成类型、参数、名称及其他相关信息方法和属性的XML文档注释。
  2. helpndoc:helpndoc是一个创建帮助文件的工具。它可以从单个源生成不同格式的文件。


  1. FileZilla:FileZilla是一个免费的FTP解决方案。FileZilla Client用于FTP文件上传,FileZilla Server用于文件共享。
  2. TreeTrim:TreeTrim是用于修整源代码树的工具。它消除了调试文件,源代码控制绑定和临时文件。
  3. BrowserStack:跨浏览器测试网站。
  4. Firebug:功能丰富的针对于CSS,HTML和JavaScript开发关于生成网页的Firefox插件。
  5. BugShooting:屏幕截图软件,截屏并放到工作项,bug,问题跟踪项等。
  6. Web developer checklist:确保web开发最佳实践。
  7. XRAY:Firefox插件。功能丰富的书签。提供有关网页元素的信息。
  8. PowerGUI:有助于快速接纳和使用PowerShell来高效管理完整的Windows环境。
  9. Beyond Compare:它允许比较目录树和单个文件的内容。适应强,有流行语言的插件。 [由Ron Matuszek提供]
  10. Devart Codecompare:文件diff工具,读取C#,C ++,VB代码的结构。包括:文件夹比较工具,比较和合并文件和文件夹的独立app,代码审查支持。 [由Cheung Tat Ming提供]




这篇文章以及任何相关的源代码和文件,遵循 The Code Project Open License (CPOL)。


英文原文:Useful Tools for ASP.NET Developers






<code class="scala"><span class="hljs-keyword">var</span> reg = /^(\\d{<span class="hljs-number">1</span>,<span class="hljs-number">4</span>})(-|\\/)(\\d{<span class="hljs-number">1</span>,<span class="hljs-number">2</span>})\\<span class="hljs-number">2</span>(\\d{<span class="hljs-number">1</span>,<span class="hljs-number">2</span>})$/; 
<span class="hljs-keyword">var</span> r = fieldValue.<span class="hljs-keyword">match</span>(reg);             
<span class="hljs-keyword">if</span>(r==<span class="hljs-literal">null</span>)alert(<span class="hljs-symbol">'Date</span> format error!');</code>


1 . 校验密码强度


<code class="cpp">^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{<span class="hljs-number">8</span>,<span class="hljs-number">10</span>}$</code>

2. 校验中文


<code class="tex">^<span class="hljs-special">[</span><span class="hljs-command">\\</span>u4e00-<span class="hljs-command">\\</span>u9fa5<span class="hljs-special">]</span><span class="hljs-special">{</span>0,<span class="hljs-special">}</span><span class="hljs-formula">$</span></code>

3. 由数字、26个英文字母或下划线组成的字符串

<code class="tex">^<span class="hljs-command">\\</span>w+<span class="hljs-formula">$</span></code>

4. 校验E-Mail 地址


<code class="markdown">[<span class="hljs-link_label">\\w!#$%&amp;'*+/=?^_`{|}~-</span>]+(?:\\.[<span class="hljs-link_label">\\w!#$%&amp;'*+/=?^_`{|}~-</span>]+)<span class="hljs-emphasis">*@(?:[\\w](?:[\\w-]*</span>[<span class="hljs-link_label">\\w</span>])?\\.)+[<span class="hljs-link_label">\\w</span>](<span class="hljs-link_url">?:[\\w-]*[\\w]</span>)?</code>

5. 校验身份证号码

下面是身份证号码的正则校验。15 或 18位。


<code class="cpp">^[<span class="hljs-number">1</span>-<span class="hljs-number">9</span>]\\d{<span class="hljs-number">7</span>}((<span class="hljs-number">0</span>\\d)|(<span class="hljs-number">1</span>[<span class="hljs-number">0</span>-<span class="hljs-number">2</span>]))(([<span class="hljs-number">0</span>|<span class="hljs-number">1</span>|<span class="hljs-number">2</span>]\\d)|<span class="hljs-number">3</span>[<span class="hljs-number">0</span>-<span class="hljs-number">1</span>])\\d{<span class="hljs-number">3</span>}$</code>


<code class="cpp">^[<span class="hljs-number">1</span>-<span class="hljs-number">9</span>]\\d{<span class="hljs-number">5</span>}[<span class="hljs-number">1</span>-<span class="hljs-number">9</span>]\\d{<span class="hljs-number">3</span>}((<span class="hljs-number">0</span>\\d)|(<span class="hljs-number">1</span>[<span class="hljs-number">0</span>-<span class="hljs-number">2</span>]))(([<span class="hljs-number">0</span>|<span class="hljs-number">1</span>|<span class="hljs-number">2</span>]\\d)|<span class="hljs-number">3</span>[<span class="hljs-number">0</span>-<span class="hljs-number">1</span>])\\d{<span class="hljs-number">3</span>}([<span class="hljs-number">0</span>-<span class="hljs-number">9</span>]|X)$</code>

6. 校验日期

“yyyy-mm-dd“ 格式的日期校验,已考虑平闰年。

<code class="markdown">^(?:(?!0000)[<span class="hljs-link_label">0-9</span>]{4}-(?:(?:0[<span class="hljs-link_label">1-9</span>]|1[<span class="hljs-link_label">0-2</span>])-(?:0[<span class="hljs-link_label">1-9</span>]|1[<span class="hljs-link_label">0-9</span>]|2[<span class="hljs-link_label">0-8</span>])|(?:0[<span class="hljs-link_label">13-9</span>]|1[<span class="hljs-link_label">0-2</span>])-(?:29|30)|(?:0[<span class="hljs-link_label">13578</span>]|1[<span class="hljs-link_label">02</span>])-31)|(?:[<span class="hljs-link_label">0-9</span>]{2}(?:0[<span class="hljs-link_label">48</span>]|[<span class="hljs-link_label">2468</span>][<span class="hljs-link_reference">048</span>]|[<span class="hljs-link_label">13579</span>][<span class="hljs-link_reference">26</span>])|(?:0[<span class="hljs-link_label">48</span>]|[<span class="hljs-link_label">2468</span>][<span class="hljs-link_reference">048</span>]|[<span class="hljs-link_label">13579</span>][<span class="hljs-link_reference">26</span>])00)-02-29)$</code>

7. 校验金额


<code class="cpp">^[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>]+(.[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>]{<span class="hljs-number">2</span>})?$</code>

8. 校验手机号

下面是国内 13、15、18开头的手机号正则表达式。(可根据目前国内收集号扩展前两位开头号码)

<code class="cpp">^(<span class="hljs-number">13</span>[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>]|<span class="hljs-number">14</span>[<span class="hljs-number">5</span>|<span class="hljs-number">7</span>]|<span class="hljs-number">15</span>[<span class="hljs-number">0</span>|<span class="hljs-number">1</span>|<span class="hljs-number">2</span>|<span class="hljs-number">3</span>|<span class="hljs-number">5</span>|<span class="hljs-number">6</span>|<span class="hljs-number">7</span>|<span class="hljs-number">8</span>|<span class="hljs-number">9</span>]|<span class="hljs-number">18</span>[<span class="hljs-number">0</span>|<span class="hljs-number">1</span>|<span class="hljs-number">2</span>|<span class="hljs-number">3</span>|<span class="hljs-number">5</span>|<span class="hljs-number">6</span>|<span class="hljs-number">7</span>|<span class="hljs-number">8</span>|<span class="hljs-number">9</span>])\\d{<span class="hljs-number">8</span>}$</code>

9. 判断IE的版本


<code class="cpp">^.*MSIE [<span class="hljs-number">5</span>-<span class="hljs-number">8</span>](?:\\.[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>]+)?(?!.*Trident\\/[<span class="hljs-number">5</span>-<span class="hljs-number">9</span>]\\<span class="hljs-number">.0</span>).*$</code>

10. 校验IP-v4地址

IP4 正则语句。

<code class="markdown">\\b(?:(?:25[<span class="hljs-link_label">0-5</span>]|2[<span class="hljs-link_label">0-4</span>][<span class="hljs-link_reference">0-9</span>]|[<span class="hljs-link_label">01</span>]?[<span class="hljs-link_label">0-9</span>][<span class="hljs-link_reference">0-9</span>]?)\\.){3}(?:25[<span class="hljs-link_label">0-5</span>]|2[<span class="hljs-link_label">0-4</span>][<span class="hljs-link_reference">0-9</span>]|[<span class="hljs-link_label">01</span>]?[<span class="hljs-link_label">0-9</span>][<span class="hljs-link_reference">0-9</span>]?)\\b</code>

11. 校验IP-v6地址

IP6 正则语句。

<code class="cpp">(([<span class="hljs-number">0</span>-<span class="hljs-number">9</span>a-fA-F]{<span class="hljs-number">1</span>,<span class="hljs-number">4</span>}:){<span class="hljs-number">7</span>,<span class="hljs-number">7</span>}[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>a-fA-F]{<span class="hljs-number">1</span>,<span class="hljs-number">4</span>}|([<span class="hljs-number">0</span>-<span class="hljs-number">9</span>a-fA-F]{<span class="hljs-number">1</span>,<span class="hljs-number">4</span>}:){<span class="hljs-number">1</span>,<span class="hljs-number">7</span>}:|([<span class="hljs-number">0</span>-<span class="hljs-number">9</span>a-fA-F]{<span class="hljs-number">1</span>,<span class="hljs-number">4</span>}:){<span class="hljs-number">1</span>,<span class="hljs-number">6</span>}:[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>a-fA-F]{<span class="hljs-number">1</span>,<span class="hljs-number">4</span>}|([<span class="hljs-number">0</span>-<span class="hljs-number">9</span>a-fA-F]{<span class="hljs-number">1</span>,<span class="hljs-number">4</span>}:){<span class="hljs-number">1</span>,<span class="hljs-number">5</span>}(:[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>a-fA-F]{<span class="hljs-number">1</span>,<span class="hljs-number">4</span>}){<span class="hljs-number">1</span>,<span class="hljs-number">2</span>}|([<span class="hljs-number">0</span>-<span class="hljs-number">9</span>a-fA-F]{<span class="hljs-number">1</span>,<span class="hljs-number">4</span>}:){<span class="hljs-number">1</span>,<span class="hljs-number">4</span>}(:[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>a-fA-F]{<span class="hljs-number">1</span>,<span class="hljs-number">4</span>}){<span class="hljs-number">1</span>,<span class="hljs-number">3</span>}|([<span class="hljs-number">0</span>-<span class="hljs-number">9</span>a-fA-F]{<span class="hljs-number">1</span>,<span class="hljs-number">4</span>}:){<span class="hljs-number">1</span>,<span class="hljs-number">3</span>}(:[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>a-fA-F]{<span class="hljs-number">1</span>,<span class="hljs-number">4</span>}){<span class="hljs-number">1</span>,<span class="hljs-number">4</span>}|([<span class="hljs-number">0</span>-<span class="hljs-number">9</span>a-fA-F]{<span class="hljs-number">1</span>,<span class="hljs-number">4</span>}:){<span class="hljs-number">1</span>,<span class="hljs-number">2</span>}(:[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>a-fA-F]{<span class="hljs-number">1</span>,<span class="hljs-number">4</span>}){<span class="hljs-number">1</span>,<span class="hljs-number">5</span>}|[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>a-fA-F]{<span class="hljs-number">1</span>,<span class="hljs-number">4</span>}:((:[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>a-fA-F]{<span class="hljs-number">1</span>,<span class="hljs-number">4</span>}){<span class="hljs-number">1</span>,<span class="hljs-number">6</span>})|:((:[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>a-fA-F]{<span class="hljs-number">1</span>,<span class="hljs-number">4</span>}){<span class="hljs-number">1</span>,<span class="hljs-number">7</span>}|:)|fe80:(:[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>a-fA-F]{<span class="hljs-number">0</span>,<span class="hljs-number">4</span>}){<span class="hljs-number">0</span>,<span class="hljs-number">4</span>}%[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>a-zA-Z]{<span class="hljs-number">1</span>,}|::(ffff(:<span class="hljs-number">0</span>{<span class="hljs-number">1</span>,<span class="hljs-number">4</span>}){<span class="hljs-number">0</span>,<span class="hljs-number">1</span>}:){<span class="hljs-number">0</span>,<span class="hljs-number">1</span>}((<span class="hljs-number">25</span>[<span class="hljs-number">0</span>-<span class="hljs-number">5</span>]|(<span class="hljs-number">2</span>[<span class="hljs-number">0</span>-<span class="hljs-number">4</span>]|<span class="hljs-number">1</span>{<span class="hljs-number">0</span>,<span class="hljs-number">1</span>}[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>]){<span class="hljs-number">0</span>,<span class="hljs-number">1</span>}[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>])\\.){<span class="hljs-number">3</span>,<span class="hljs-number">3</span>}(<span class="hljs-number">25</span>[<span class="hljs-number">0</span>-<span class="hljs-number">5</span>]|(<span class="hljs-number">2</span>[<span class="hljs-number">0</span>-<span class="hljs-number">4</span>]|<span class="hljs-number">1</span>{<span class="hljs-number">0</span>,<span class="hljs-number">1</span>}[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>]){<span class="hljs-number">0</span>,<span class="hljs-number">1</span>}[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>])|([<span class="hljs-number">0</span>-<span class="hljs-number">9</span>a-fA-F]{<span class="hljs-number">1</span>,<span class="hljs-number">4</span>}:){<span class="hljs-number">1</span>,<span class="hljs-number">4</span>}:((<span class="hljs-number">25</span>[<span class="hljs-number">0</span>-<span class="hljs-number">5</span>]|(<span class="hljs-number">2</span>[<span class="hljs-number">0</span>-<span class="hljs-number">4</span>]|<span class="hljs-number">1</span>{<span class="hljs-number">0</span>,<span class="hljs-number">1</span>}[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>]){<span class="hljs-number">0</span>,<span class="hljs-number">1</span>}[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>])\\.){<span class="hljs-number">3</span>,<span class="hljs-number">3</span>}(<span class="hljs-number">25</span>[<span class="hljs-number">0</span>-<span class="hljs-number">5</span>]|(<span class="hljs-number">2</span>[<span class="hljs-number">0</span>-<span class="hljs-number">4</span>]|<span class="hljs-number">1</span>{<span class="hljs-number">0</span>,<span class="hljs-number">1</span>}[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>]){<span class="hljs-number">0</span>,<span class="hljs-number">1</span>}[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>]))</code>

12. 检查URL的前缀


<code class="scala"><span class="hljs-keyword">if</span> (!s.<span class="hljs-keyword">match</span>(/^[a-zA-<span class="hljs-type">Z</span>]+:\\/\\<span class="hljs-comment">//))</span>
    s = <span class="hljs-symbol">'http</span>:<span class="hljs-comment">//' + s;</span>

13. 提取URL链接


<code class="tex">^(f|ht)<span class="hljs-special">{</span>1<span class="hljs-special">}</span>(tp|tps):<span class="hljs-command">\\</span>/<span class="hljs-command">\\</span>/(<span class="hljs-special">[</span><span class="hljs-command">\\</span>w-<span class="hljs-special">]</span>+<span class="hljs-command">\\</span>.)+<span class="hljs-special">[</span><span class="hljs-command">\\</span>w-<span class="hljs-special">]</span>+(<span class="hljs-command">\\</span>/<span class="hljs-special">[</span><span class="hljs-command">\\</span>w- ./?<span class="hljs-comment">%&amp;=]*)?</span></code>

14. 文件路径及扩展名校验


<code class="tex">^(<span class="hljs-special">[</span>a-zA-Z<span class="hljs-special">]</span><span class="hljs-command">\\</span>:|<span class="hljs-command">\\</span><span class="hljs-command">\\</span>)<span class="hljs-command">\\</span><span class="hljs-command">\\</span>(<span class="hljs-special">[</span>^<span class="hljs-command">\\</span><span class="hljs-command">\\</span><span class="hljs-special">]</span>+<span class="hljs-command">\\</span><span class="hljs-command">\\</span>)*<span class="hljs-special">[</span>^<span class="hljs-command">\\</span>/:*?"&lt;&gt;|<span class="hljs-special">]</span>+<span class="hljs-command">\\</span>.txt(l)?<span class="hljs-formula">$</span></code>

15. 提取Color Hex Codes


<code class="cpp">^<span class="hljs-preprocessor">#([A-Fa-f0-<span class="hljs-number">9</span>]{<span class="hljs-number">6</span>}|[A-Fa-f0-<span class="hljs-number">9</span>]{<span class="hljs-number">3</span>})$</span></code>

16. 提取网页图片


<code class="tex"><span class="hljs-command">\\</span>&lt; *<span class="hljs-special">[</span>img<span class="hljs-special">]</span><span class="hljs-special">[</span>^<span class="hljs-command">\\</span><span class="hljs-command">\\</span>&gt;<span class="hljs-special">]</span>*<span class="hljs-special">[</span>src<span class="hljs-special">]</span> *= *<span class="hljs-special">[</span><span class="hljs-command">\\</span>"<span class="hljs-command">\\</span>'<span class="hljs-special">]</span><span class="hljs-special">{</span>0,1<span class="hljs-special">}</span>(<span class="hljs-special">[</span>^<span class="hljs-command">\\</span>"<span class="hljs-command">\\</span>'<span class="hljs-command">\\</span> &gt;<span class="hljs-special">]</span>*)</code>

17. 提取页面超链接


<code class="tex">(&lt;a<span class="hljs-command">\\</span>s*(?!.*<span class="hljs-command">\\</span>brel=)<span class="hljs-special">[</span>^&gt;<span class="hljs-special">]</span>*)(href="https?:<span class="hljs-command">\\</span>/<span class="hljs-command">\\</span>/)((?!(?:(?:www<span class="hljs-command">\\</span>.)?'.implode('|(?:www<span class="hljs-command">\\</span>.)?', <span class="hljs-formula">$follow_list).'))<span class="hljs-special">[</span>^"<span class="hljs-special">]</span>+)"((?!.*<span class="hljs-command">\\</span>brel=)<span class="hljs-special">[</span>^&gt;<span class="hljs-special">]</span>*)(?:<span class="hljs-special">[</span>^&gt;<span class="hljs-special">]</span>*)&gt;</span></code>

18. 查找CSS属性


<code class="tex">^<span class="hljs-command">\\</span>s*<span class="hljs-special">[</span>a-zA-Z<span class="hljs-command">\\</span>-<span class="hljs-special">]</span>+<span class="hljs-command">\\</span>s*<span class="hljs-special">[</span>:<span class="hljs-special">]</span><span class="hljs-special">{</span>1<span class="hljs-special">}</span><span class="hljs-command">\\</span>s<span class="hljs-special">[</span>a-zA-Z0-9<span class="hljs-command">\\</span>s.<span class="hljs-special">#</span><span class="hljs-special">]</span>+<span class="hljs-special">[</span>;<span class="hljs-special">]</span><span class="hljs-special">{</span>1<span class="hljs-special">}</span></code>

19. 抽取注释


<code class="xml"><span class="hljs-comment">&lt;!--(.*?)--&gt;</span></code>

20. 匹配HTML标签


<code class="tex">&lt;<span class="hljs-command">\\</span>/?<span class="hljs-command">\\</span>w+((<span class="hljs-command">\\</span>s+<span class="hljs-command">\\</span>w+(<span class="hljs-command">\\</span>s*=<span class="hljs-command">\\</span>s*(?:".*?"|'.*?'|<span class="hljs-special">[</span><span class="hljs-command">\\</span>^'"&gt;<span class="hljs-command">\\</span>s<span class="hljs-special">]</span>+))?)+<span class="hljs-command">\\</span>s*|<span class="hljs-command">\\</span>s*)<span class="hljs-command">\\</span>/?&gt;</code>


下面是我找到的一张非常不错的正则表达式 Cheat Sheet,可以用来快速查找相关语法。






Connecting to MS SQL Server from Ubuntu


And now, in a break from the previous trend of fluffy posts, we have a tutorial on how to (deep breath): connect PHP to a MSSQL Server 2008 instance over ODBC from Ubuntu Linux using the FreeTDS driver and unixODBC. Theoretically it would also work for SQL Server 2005.

I don’t know whether half of the settings flags are necessary or even correct, but what follows Worked for Me™, YMMV, etc, etc.

In the commands below, I’ll use as the server housing the SQL Server instance, with a SQL Server user name of devuser, password devpass. I’m assuming SQL Server is set up to listen on its default port, 1433. Keep an eye out, because you’ll need to change these things to your own settings.

First, install unixODBC:

sudo apt-get install unixodbc unixodbc-dev

I also installed the following (perhaps necessary) packages:
sudo apt-get install tdsodbc php5-odbc
Then download, untar, compile, and install FreeTDS (warning, the URL may change):
cd /usr/local
tar xvfz freetds-stable.tgz
cd freetds-0.82
./configure --enable-msdblib --with-tdsver=8.0 --with-unixodbc=/usr
make install
make clean

Attempt a connection over Telnet to your SQL Server instance:
telnet 1433

Use the tsql tool to test out the connection:
tsql -S -U devuser

This should prompt you for the password, after which you can hope against hope to see this beautiful sign:

If that worked, I recommend throwing a (coding) party. Next up is some configging. Open the FreeTDS config file.

Add the following entry to the bottom of the file. We’re setting up a datasource name (DSN) called ‘MSSQL’.
host =
port = 1433
tds version = 8.0

Now open the ODBC configuration file:

And add the following MSSQL driver entry (FreeTDS) at the end:
Description = FreeTDS driver
Driver = /usr/local/lib/
FileUsage = 1
UsageCount = 1 

Then, finally, set up the DSN within ODBC in the odbc.ini file here
By adding this bit to the file:
Description = MS SQL Server
Driver = /usr/local/lib/
Server =
UID = devuser
PWD = devpass
ReadOnly = No
Port = 1433

Test out the connection using the isql tool:
isql -v MSSQL devuser 'devpass'
If you see “Connected!” you’re golden, congratulations! If not, I’m truly sorry; see below where there are some resources that might help.

Now restart Apache and test it from PHP using ‘MSSQL’ as the DSN. If something doesn’t work, you might try installing any or all of these packages:
mdbtools libmdbodbc libmdbtools mdbtools-gmdb

Here are some other resources that were helpful to me through this disastrous journey.

Eight Terminal Utilities Every OS X Command Line User Should Know


The OS X Terminal opens up a world of powerful UNIX utilities and scripts. If you’re migrating from Linux, you’ll find many familiar commands work the way you expect. But power users often aren’t aware that OS X comes with a number of its own text-based utilities not found on any other operating system. Learning about these Mac-only programs can make you more productive on the command line and help you bridge the gap between UNIX and your Mac.

Update: Thanks to reader feedback, I’ve written about a few more commands in a follow-up post: (And eight hundred more).

1. open

open opens files, directories and applications. Exciting, right? But it really does come in handy as a command-line double-click. For instance, typing:

<code class=" hljs ruby"><span class="hljs-variable">$ </span>open /<span class="hljs-constant">Applications</span>/<span class="hljs-constant">Safari</span>.app/

…will launch Safari as if you had double-clicked its icon in the Finder.

If you point open at a file instead, it will try to load the file with its associated GUI application. open screenshot.png on an image will open that image in Preview. You can set the -a flag to choose the app yourself, or -e to open the file for editing in TextEdit.

Running open on a directory will take you straight to that directory in a Finder window. This is especially useful for bringing up the current directory by typing open .

Remember that the integration between Finder and Terminal goes both ways – if you drag a file from Finder into a Terminal window, its full path gets pasted into the command line.

2. pbcopy and pbpaste

These two commands let you copy and paste text from the command line. Of course, you could also just use your mouse—but the real power of pbcopy and pbpaste comes from the fact that they’re UNIX commands, and that means they benefit from piping, redirection, and the ability to be in scripts in conjunction with other commands. Typing:

<code class=" hljs ruby"><span class="hljs-variable">$ </span>ls ~ | pbcopy

…will copy a list of files in your home directory to the OS X clipboard. You can easily capture the contents of a file:

<code class=" hljs ruby"><span class="hljs-variable">$ </span>pbcopy &lt; blogpost.txt

..or do something crazier. This hacked-up script will grab the link of the latest Google doodle and copy it to your clipboard.

<code class=" hljs coffeescript">$ curl <span class="hljs-attribute">http</span>:<span class="hljs-regexp">//</span><span class="hljs-regexp">/doodles#oodles/archive | grep -A5 'latest-doodle on' | grep 'img src' | sed s/</span>.*<span class="hljs-string">'&lt;img src="\/\/'</span><span class="hljs-regexp">/''/</span> | sed s<span class="hljs-regexp">/'" alt=".*'/</span><span class="hljs-string">''</span>/ | pbcopy

Using pbcopy with pipes is a great way to capture the output of a command without having to scroll up and carefully select it. This makes it easy to share diagnostic information. pbcopy and pbpaste can also be used to automate or speed up certain kinds of tasks. For instance, if you want to save email subject lines to a task list, you could copy the subjects from and run:

<code class=" hljs ruby"><span class="hljs-variable">$ </span>pbpaste &gt;&gt; tasklist.txt

3. mdfind

Many a Linux power user has tried to use locate to search for files on a Mac and then quickly discovered that it didn’t work. There’s always the venerable UNIX find command, but OS X comes with its own killer search tool: Spotlight. So why not tap into its power from the command line?

That’s exactly what mdfind does. Anything Spotlight can find, mdfind can find too. That includes the ability to search inside files and metadata.

mdfind comes with a few conveniences that make it stand out from its big blue brother. For instance, the -onlyin flag can restrict the search to a single directory:

<code class=" hljs ">$ mdfind -onlyin ~/Documents essay

The mdfind database should stay up to date in the background, but you can also troubleshoot it (as well as Spotlight) using mdutil. If Spotlight isn’t working the way it should, mdutil -E will erase the index and rebuild it from scratch. You can also turn off indexing entirely with mdutil -i off.

4. screencapture

screencapture lets you take many different kinds of screenshots. It’s similar to and the keyboard shortcuts cmd + shift + 3 and cmd + shift + 4, except it’s far more flexible. Here are just a few different ways you can use screencapture:

Capture the contents of the screen, including the cursor, and attach the resulting image (named ‘image.png’) to a new Mail message:

<code class=" hljs ruby"><span class="hljs-variable">$ </span>screencapture -<span class="hljs-constant">C</span> -<span class="hljs-constant">M</span> image.png

Select a window using your mouse, then capture its contents without the window’s drop shadow and copy the image to the clipboard:

<code class=" hljs ruby"><span class="hljs-variable">$ </span>screencapture -c -<span class="hljs-constant">W</span>

Capture the screen after a delay of 10 seconds and then open the new image in Preview:

<code class=" hljs ruby"><span class="hljs-variable">$ </span>screencapture -<span class="hljs-constant">T</span> <span class="hljs-number">10</span> -<span class="hljs-constant">P</span> image.png

Select a portion of the screen with your mouse, capture its contents, and save the image as a pdf:

<code class=" hljs bash">$ screencapture <span class="hljs-operator">-s</span> -t pdf image.pdf

To see more options, type screencapture --help

5. launchctl

launchctl lets you interact with the OS X init script system, launchd. With launch daemons and launch agents, you can control the services that start up when you boot your computer. You can even set up scripts to run periodically or at timed intervals in the background, similar to cron jobs on Linux.

For example, if you’d like to have the Apache web server start automatically when you turn on your Mac, simply type:

<code class=" hljs bash">$ <span class="hljs-built_in">sudo</span> launchctl load -w /System/Library/LaunchDaemons/org.apache.httpd.plist

Running launchctl list will show you what launch scripts are currently loaded. sudo launchctl unload [path/to/script] will stop and unload running scripts, and adding the -w flag will remove those scripts permanently from your boot sequence. I like to run this one on all the auto-update “helpers” created by Adobe apps and Microsoft Office.

Launchd scripts are stored in the folllowing locations:

<code class=" hljs ruby">~<span class="hljs-regexp">/Library/</span><span class="hljs-constant">LaunchAgents</span>    
/<span class="hljs-constant">Library</span>/<span class="hljs-constant">LaunchAgents</span>          
/<span class="hljs-constant">Library</span>/<span class="hljs-constant">LaunchDaemons</span>
/<span class="hljs-constant">System</span>/<span class="hljs-constant">Library</span>/<span class="hljs-constant">LaunchAgents</span>
/<span class="hljs-constant">System</span>/<span class="hljs-constant">Library</span>/<span class="hljs-constant">LaunchDaemons</span>

To see what goes into a launch agent or daemon, there’s a great blog post by Paul Annesley that walks you through the file format. And if you’d like to learn how to write your own launchd scripts, Apple provides some helpful documentation on their Developer site. There’s also the fantastic Lingon app if you’d prefer to avoid the command line entirely.

6. say

This is a fun one: say converts text to speech, using the same TTS engine OS X uses for VoiceOver. Without any options, say will simply speak whatever text you give it out loud.:

<code class=" hljs ruby"><span class="hljs-variable">$ </span>say <span class="hljs-string">"Never trust a computer you can't lift."</span>

You can also use say to speak the contents of a text file with the -f flag, and you can store the resulting audio clip with the -o flag:

<code class=" hljs bash">$ say <span class="hljs-operator">-f</span> mynovel.txt -o myaudiobook.aiff

The say command can be useful in place of console logging or alert sounds in scripts. For instance, you can set up an Automator or Hazel script to do batch file processing and then announce the task’s completion with say.

But the most enjoyable use for say is rather more sinister: if you have ssh access to a friend or coworker’s Mac, you can silently log into their machine and haunt them through the command line. Give ‘em a Siri-ous surprise.

You can set the voice (and language!) used by say by changing the default setting in the Dictation & Speech panel in System Preferences.

7. diskutil

diskutil is a command line interface to the Disk Utility app that comes with OS X. It can do everything its graphical cousin can, but it also has some extra capabilities—such as filling a disk with zeroes or random data. Simply type diskutil list to see the path names of disks and removable media attached to your machine, and then point the command at the volume you want to operate on. Be careful: diskutil can permanently destroy data if it’s used incorrectly.

8. brew

Alright–this isn’t technically a native command. But no OS X power user should be without Homebrew. The website calls it “The missing package manager for OS X,” and that couldn’t be truer. If you’ve ever used apt-get in Linux, you will feel right at home in Homebrew.

brew gives you easy access to thousands of free utilities and libraries from the open source community. For instance, brew install imagemagick will set you up with ImageMagick, a powerful utility that makes it possible to do anything from whipping up animated gifs to converting images between dozens of different types. brew install node will introduce you to NodeJS, the hot new tool for developing and running server-side JavaScript apps.

You can have fun with Homebrew too: brew install archey will get you Archey, a cool little script for displaying your Mac’s specs next to a colourful Apple logo. The selection in Homebrew is huge—and because it’s so easy to create formulas, new packages are being added all the time.

ARCHEY—My command line brings all the boys to the yard.

But the best part about Homebrew? It keeps all its files in a single directory: /usr/local/. That means you can install newer versions of system software, such as python and mysql, without interfering with the built-in equivalents. And if you ever want to get rid of your Homebrew installation, it’s easy to remove.

Edit—May 15: Someone suggested to me that that you should not blindly delete the contents of /usr/local/. That’s a fair precaution. To remove Homebrew safely, use the uninstall script.

For more fun with, here is an A-Z list of all available console commands in OS X 10.9 Mavericks.

80 Linux Monitoring Tools for SysAdmins


By Jonathan Sundqvist, Engineer at Server Density.
Published on the 4th February, 2015.


The industry is hotting up at the moment, and there are more tools than you can shake a stick at. Here lies the most comprehensive list on the Internet (of monitoring tools). Featuring over 80 ways to monitor your machines. Within this article we outline:

  • Command line tools
  • Network related
  • System related monitoring
  • Log monitoring tools
  • Infrastructure monitoring tools

It’s hard work monitoring and debugging performance problems, but it’s easier with the right tools at the right time. But how much of your valuable time do you think it would take you to investigate all of these tools and find out which one is best for you?

Why not check out Server Density first, it has a beautiful UI, an api that’s easy to use and alerts that will keep downtime to a minimum.


Top 10  System Monitoring Tools

1. Top

This is a small tool which is pre-installed in many unix systems. When you want an overview of all the processes or threads running in the system: top is a good tool. You can order these processes on different criteria and the default criteria is CPU.

2. htop

Htop is essentially an enhanced version of top. It’s easier to sort by processes. It’s visually easier to understand and has built in commands for common things you would like to do. Plus it’s fully interactive.

3. atop

Atop monitors all processes much like top and htop, unlike top and htop however it has daily logging of the processes for long-term analysis. It also shows resource consumption by all processes. It will also highlight resources that have reached a critical load.

4. apachetop

Apachetop monitors the overall performance of your apache webserver. It’s largely based on mytop. It displays current number of reads, writes and the overall number of requests processed.

5. ftptop

ftptop gives you basic information of all the current ftp connections to your server such as the total amount of sessions, how many are uploading and downloading and who the client is.

6. mytop

mytop is a neat tool for monitoring threads and performance of mysql. It gives you a live look into the database and what queries it’s processing in real time.

7. powertop

powertop helps you diagnose issues that has to do with power consumption and power management. It can also help you experiment with power management settings to achieve the most efficient settings for your server. You switch tabs with the tab key.

8. iotop

iotop checks the I/O usage information and gives you a top-like interface to that. It displays columns on read and write and each row represents a process. It also displays the percentage of time the process spent while swapping in and while waiting on I/O.

Network related monitoring

9. ntopng

ntopng is the next generation of ntop and the tool provides a graphical user interface via the browser for network monitoring. It can do stuff such as: geolocate hosts, get network traffic and show ip traffic distribution and analyze it.

10. iftop

iftop is similar to top, but instead of mainly checking for cpu usage it listens to network traffic on selected network interfaces and displays a table of current usage. It can be handy for answering questions such as “Why on earth is my internet connection so slow?!”.

11. jnettop

jnettop visualises network traffic in much the same way as iftop does. It also supports customizable text output and a machine-friendly mode to support further analysis.

12. bandwidthd

BandwidthD tracks usage of TCP/IP network subnets and visualises that in the browser by building a html page with graphs in png. There is a database driven system that supports searching, filtering, multiple sensors and custom reports.

13. EtherApe

EtherApe displays network traffic graphically, the more talkative the bigger the node. It either captures live traffic or can read it from a tcpdump. The displayed can also be refined using a network filter with pcap syntax.

14. ethtool

ethtool is used for displaying and modifying some parameters of the network interface controllers. It can also be used to diagnose Ethernet devices and get more statistics from the devices.

15. NetHogs

NetHogs breaks down network traffic per protocol or per subnet. It then groups by process. So if there’s a surge in network traffic you can fire up NetHogs and see which process is causing it.

16. iptraf

iptraf gathers a variety of metrics such as TCP connection packet and byte count, interface statistics and activity indicators, TCP/UDP traffic breakdowns and station packet and byte counts.

17. ngrep

ngrep is grep but for the network layer. It’s pcap aware and will allow to specify extended regular or hexadecimal expressions to match against packets of .

18. MRTG

MRTG was orginally developed to monitor router traffic, but now it’s able to monitor other network related things as well. It typically collects every five minutes and then generates a html page. It also has the capability of sending warning emails.

19. bmon

Bmon monitors and helps you debug networks. It captures network related statistics and presents it in human friendly way. You can also interact with bmon through curses or through scripting.

20. traceroute

Traceroute is a built-in tool for displaying the route and measuring the delay of packets across a network.

21. IPTState

IPTState allows you to watch where traffic that crosses your iptables is going and then sort that by different criteria as you please. The tool also allows you to delete states from the table.

22. darkstat

Darkstat captures network traffic and calculates statistics about usage. The reports are served over a simple HTTP server and gives you a nice graphical user interface of the graphs.

23. vnStat

vnStat is a network traffic monitor that uses statistics provided by the kernel which ensures light use of system resources. The gathered statistics persists through system reboots. It has color options for the artistic sysadmins.

24. netstat

Netstat is a built-in tool that displays TCP network connections, routing tables and a number of network interfaces. It’s used to find problems in the network.

25. ss

Instead of using netstat, it’s however preferable to use ss. The ss command is capable of showing more information than netstat and is actually faster. If you want a summary statistics you can use the command ss -s.

26. nmap

Nmap allows you to scan your server for open ports or detect which OS is being used. But you could also use this for SQL injection vulnerabilities, network discovery and other means related to penetration testing.

27. MTR

MTR combines the functionality of traceroute and the ping tool into a single network diagnostic tool. When using the tool it will limit the number hops individual packets has to travel while also listening to their expiry. It then repeats this every second.

28. Tcpdump

Tcpdump will output a description of the contents of the packet it just captured which matches the expression that you provided in the command. You can also save the this data for further analysis.

29. Justniffer

Justniffer is a tcp packet sniffer. You can choose whether you would like to collect low-level data or high-level data with this sniffer. It also allows you to generate logs in customizable way. You could for instance mimic the access log that apache has.

System related monitoring

30. nmon

nmon either outputs the data on screen or saves it in a comma separated file. You can display CPU, memory, network, filesystems, top processes. The data can also be added to a RRD database for further analysis.

31. conky

Conky monitors a plethora of different OS stats. It has support for IMAP and POP3 and even support for many popular music players! For the handy person you could extend it with your own scripts or programs using Lua.

32. Glances

Glances monitors your system and aims to present a maximum amount of information in a minimum amount of space. It has the capability to function in a client/server mode as well as monitoring remotely. It also has a web interface.

33. saidar

Saidar is a very small tool that gives you basic information about your system resources. It displays a full screen of the standard system resources. The emphasis for saidar is being as simple as possible.

34. RRDtool

RRDtool is a tool developed to handle round-robin databases or RRD. RRD aims to handle time-series data like CPU load, temperatures etc. This tool provides a way to extract RRD data in a graphical format.

35. monit

Monit has the capability of sending you alerts as well as restarting services if they run into trouble. It’s possible to perform any type of check you could write a script for with monit and it has a web user interface to ease your eyes.

36. Linux process explorer

Linux process explorer is akin to the activity monitor for OSX or the windows equivalent. It aims to be more usable than top or ps. You can view each process and see how much memory usage or CPU it uses.

37. df

df is an abbreviation for disk free and is pre-installed program in all unix systems used to display the amount of available disk space for filesystems which the user have access to.

38. discus

Discus is similar to df however it aims to improve df by making it prettier using fancy features as colors, graphs and smart formatting of numbers.

39. xosview

xosview is a classic system monitoring tool and it gives you a simple overview of all the different parts of the including IRQ.

40. Dstat

Dstat aims to be a replacement for vmstat, iostat, netstat and ifstat. It allows you to view all of your system resources in real-time. The data can then be exported into csv. Most importantly dstat allows for plugins and could thus be extended into areas not yet known to mankind.

41. Net-SNMP

SNMP is the protocol ‘simple network management protocol’ and the Net-SNMP tool suite helps you collect accurate information about your servers using this protocol.

42. incron

Incron allows you to monitor a directory tree and then take action on those changes. If you wanted to copy files to directory ‘b’ once new files appeared in directory ‘a’ that’s exactly what incron does.

43. monitorix

Monitorix is lightweight system monitoring tool. It helps you monitor a single machine and gives you a wealth of metrics. It also has a built-in HTTP server to view graphs and a reporting mechanism of all metrics.

44. vmstat

vmstat or virtual memory statistics is a small built-in tool that monitors and displays a summary about the memory in the machine.

45. uptime

This small command that quickly gives you information about how long the machine has been running, how many users currently are logged on and the system load average for the past 1, 5 and 15 minutes.

46. mpstat

mpstat is a built-in tool that monitors cpu usage. The most common command is using mpstat -P ALL which gives you the usage of all the cores. You can also get an interval update of the CPU usage.

47. pmap

pmap is a built-in tool that reports the memory map of a process. You can use this command to find out causes of memory bottlenecks.

48. ps

The ps command will give you an overview of all the current processes. You can easily select all processes using the command ps -A

49. sar

sar is a part of the sysstat package and helps you to collect, report and save different system metrics. With different commands it will give you CPU, memory and I/O usage among other things.

50. collectl

Similar to sar collectl collects performance metrics for your machine. By default it shows cpu, network and disk stats but it collects a lot more. The difference to sar is collectl is able to deal with times below 1 second, it can be fed into a plotting tool directly and collectl monitors processes more extensively.

51. iostat

iostat is also part of the sysstat package. This command is used for monitoring system input/output. The reports themselves can be used to change system configurations to better balance input/output load between hard drives in your machine.

52. free

This is a built-in command that displays the total amount of free and used physical memory on your machine. It also displays the buffers used by the kernel at that given moment.

53. /Proc file system

The proc file system gives you a peek into kernel statistics. From these statistics you can get detailed information about the different hardware devices on your machine. Take a look at the full list of the proc file statistics

54. GKrellM

GKrellm is a gui application that monitor the status of your hardware such CPU, main memory, hard disks, network interfaces and many other things. It can also monitor and launch a mail reader of your choice.

55. Gnome system monitor

Gnome system monitor is a basic system monitoring tool that has features looking at process dependencies from a tree view, kill or renice processes and graphs of all server metrics.

Log monitoring tools

56. GoAccess

GoAccess is a real-time web log analyzer which analyzes the access log from either apache, nginx or amazon cloudfront. It’s also possible to output the data into HTML, JSON or CSV. It will give you general statistics, top visitors, 404s, geolocation and many other things.

57. Logwatch

Logwatch is a log analysis system. It parses through your system’s logs and creates a report analyzing the areas that you specify. It can give you daily reports with short digests of the activities taking place on your machine.

58. Swatch

Much like Logwatch Swatch also monitors your logs, but instead of giving reports it watches for regular expression and notifies you via mail or the console when there is a match. It could be used for intruder detection for example.

59. MultiTail

MultiTail helps you monitor logfiles in multiple windows. You can merge two or more of these logfiles into one. It will also use colors to display the logfiles for easier reading with the help of regular expressions.

System tools

60. acct or psacct

acct or psacct (depending on if you use apt-get or yum) allows you to monitor all the commands a users executes inside the system including CPU and memory time. Once installed you get that summary with the command ‘sa’.

61. whowatch

Similar to acct this tool monitors users on your system and allows you to see in real time what commands and processes they are using. It gives you a tree structure of all the processes and so you can see exactly what’s happening.

62. strace

strace is used to diagnose, debug and monitor interactions between processes. The most common thing to do is making strace print a list of system calls made by the program which is useful if the program does not behave as expected.

63. DTrace

DTrace is the big brother of strace. It dynamically patches live running instructions with instrumentation code. This allows you to do in-depth performance analysis and troubleshooting. However, it’s not for the weak of heart as there is a 1200 book written on the topic.

64. webmin

Webmin is a web-based system administration tool. It removes the need to manually edit unix configuration files and lets you manage the system remotely if need be. It has a couple of monitoring modules that you can attach to it.

65. stat

Stat is a built-in tool for displaying status information of files and file systems. It will give you information such as when the file was modified, accessed or changed.

66. ifconfig

ifconfig is a built-in tool used to configure the network interfaces. Behind the scenes network monitor tools use ifconfig to set it into promiscuous mode to capture all packets. You can do it yourself with ifconfig eth0 promiscand return to normal mode with ifconfig eth0 -promisc.

67. ulimit

ulimit is a built-in tool that monitors system resources and keeps a limit so any of the monitored resources don’t go overboard. For instance making a fork bomb where a properly configured ulimit is in place would be totally fine.

68. cpulimit

CPUlimit is a small tool that monitors and then limits the CPU usage of a process. It’s particularly useful to make batch jobs not eat up too many CPU cycles.

69. lshw

lshw is a small built-in tool extract detailed information about the hardware configuration of the machine. It can output everything from CPU version and speed to mainboard configuration.

70. w

W is a built-in command that displays information about the users currently using the machine and their processes.

71. lsof

lsof is a built-in tool that gives you a list of all open files and network connections. From there you can narrow it down to files opened by processes, based on the process name, by a specific user or perhaps kill all processes that belongs to a specific user.

Infrastructure monitoring tools

72. Server Density

Our linux monitoring tool! It has a web interface that allows you to set alerts and view graphs for all system and network metrics. You can also set up monitoring of websites whether they are up or down. Server Density allows you to set permissions for users and you can extend your monitoring with our plugin infrastructure or api. The service already supports Nagios plugins.

73. OpenNMS

OpenNMS has four main functional areas: event management and notifications; discovery and provisioning; service monitoring and data collection. It’s designed to be customizable to work in a variety of network environments.

74. SysUsage

SysUsage monitors your system continuously via Sar and other system commands. It also allows notifications to alarm you once a threshold is reached. SysUsage itself can be run from a centralized place where all the collected statistics are also being stored. It has a web interface where you can view all the stats.

75. brainypdm

brainypdm is a data management and monitoring tool that has the capability to gather data from nagios or another generic source to make graphs. It’s cross-platform, has custom graphs and is web based.

76. PCP

PCP has the capability of collating metrics from multiple hosts and does so efficiently. It also has a plugin framework so you can make it collect specific metrics that is important to you. You can access graph data through either a web interface or a GUI. Good for monitoring large systems.

77. KDE system guard

This tool is both a system monitor and task manager. You can view server metrics from several machines through the worksheet and if a process needs to be killed or if you need to start a process it can be done within KDE system guard.

78. Munin

Munin is both a network and a system monitoring tool which offers alerts for when metrics go beyond a given threshold. It uses RRDtool to create the graphs and it has web interface to display these graphs. Its emphasis is on plug and play capabilities with a number of plugins available.

79. Nagios

Nagios is system and network monitoring tool that helps you monitor monitor your many servers. It has support for alerting for when things go wrong. It also has many plugins written for the platform.

80. Zenoss

Zenoss provides a web interface that allows you to monitor all system and network metrics. Moreover it discovers network resources and changes in network configurations. It has alerts for you to take action on and it supports the Nagios plugins.

81. Cacti

(And one for luck!) Cacti is network graphing solution that uses the RRDtool data storage. It allows a user to poll services at predetermined intervals and graph the result. Cacti can be extended to monitor a source of your choice through shell scripts.

82. Zabbix

Zabbix Monitoring
Zabbix is an open source infrastructure monitoring solution. It can use most databases out there to store the monitoring statistics. The Core is written in C and has a frontend in PHP. If you don’t like installing an agent, Zabbix might be an option for you.

Bonus section:

Thanks for your suggestions. It’s an oversight on our part that we’ll have to go back trough and renumber all the headings. In light of that, here’s a short section at the end for some of the Linux monitoring tools recommended by you:

83. collectd

Collectd is a Unix daemon that collects all your monitoring statistics. It uses a modular design and plugins to fill in any niche monitoring. This way collectd stays as lightweight and customizable as possible.

84. Observium

Observium is an auto-discovering network monitoring platform supporting a wide range of hardware platforms and operating systems. Observium focuses on providing a beautiful and powerful yet simple and intuitive interface to the health and status of your network.

85. Nload

It’s a command line tool that monitors network throughput. It’s neat because it visualizes the in and and outgoing traffic using two graphs and some additional useful data like total amount of transferred data. You can install it with


84. SmokePing

SmokePing keeps track of the network latencies of your network and it visualises them too. There are a wide range of latency measurement plugins developed for SmokePing. If a GUI is important to you it’s there is an ongoing development to make that happen.

85. MobaXterm

If you’re working in windows environment day in and day out. You may feel limited by the terminal Windows provides. MobaXterm comes to the rescue and allows you to use many of the terminal commands commonly found in Linux. Which will help you tremendously in your monitoring needs!

86. Shinken monitoring

Shinken is a monitoring framework which is a total rewrite of Nagios in python. It aims to enhance flexibility and managing a large environment. While still keeping all your nagios configuration and plugins.




1 数组中的每个元素乘以2


(1...1024).map{$0 * 2}

2 数组中的元素求和

虽然这里使用reduce和加号运算符,借助了加号运算符是函数这样一个事实,但解决办法是显而易见的,我们可以看到 reduce更具创意的用法。

(1...1024).reduce(0,combine: +)

3 验证在字符串中是否存在指定单词

让我们使用 filter来验证tweet中是否包含选定的若干关键字中的一个:

let words = ["Swift","iOS","cocoa","OSX","tvOS"]
let tweet = "This is an example tweet larking about Swift"

let valid = !words.filter({tweet.containsString($0)}).isEmpty
valid //true




  .split(" ")

4 读取文件

像其他语言一样,通过简单的内置来读取文件到数组中是不可能,但我们可以结合使用 split 和 map创造一些不需要for循环的简短代码:

let path = NSBundle.mainBundle().pathForResource("test", ofType: "txt")

let lines = try? String(contentsOfFile: path!).characters.split{$0 == "\n"}.map(String.init)
if let lines=lines {
    lines[0] // O! for a Muse of fire, that would ascend
    lines[1] // The brightest heaven of invention!
    lines[2] // A kingdom for a stage, princes to act
    lines[3] // And monarchs to behold the swelling scene.


5 祝你生日快乐!


let name = "uraimo"
(1...4).forEach{print("Happy Birthday " + (($0 == 3) ? "dear \(name)":"to You"))}

6 过滤数组中的数字

在这种情况下,我们需要使用提供的过滤函数分区一个序列。许多语言除了拥有常用的map、flatMap、reduce、filter等,还有正好能做这件事的 partitionBy 函数,Swift如你所知没有类似的东西(NSPredicate提供的可以过滤的NSArray函数在这里不是我们所需要的)。

因此,我们可以用 partitionBy 函数扩展 SequenceType 来解决这个问题,我们将使用 partitionBy 函数来分区整型数组:

extension SequenceType{
    typealias Element = Self.Generator.Element

    func partitionBy(fu: (Element)-&gt;Bool)-&gt;([Element],[Element]){
        var first=[Element]()
        var second=[Element]()
        for el in self {
            if fu(el) {
        return (first,second)

let part = [82, 58, 76, 49, 88, 90].partitionBy{$0 &lt; 60}
part // ([58, 49], [82, 76, 88, 90])


extension SequenceType{

    func anotherPartitionBy(fu: (Self.Generator.Element)-&gt;Bool)-&gt;([Self.Generator.Element],[Self.Generator.Element]){
        return (self.filter(fu),self.filter({!fu($0)}))

let part2 = [82, 58, 76, 49, 88, 90].anotherPartitionBy{$0 &lt; 60}
part2 // ([58, 49], [82, 76, 88, 90])


我们是否使用单个数据流建立一些能够将初始序列转换为分区元组的东西?是的,我们可以用 reduce

var part3 = [82, 58, 76, 49, 88, 90].reduce( ([],[]), combine: {
	(a:([Int],[Int]),n:Int) -&gt; ([Int],[Int]) in
	(n&lt;60) ? (a.0+[n],a.1) : (a.0,a.1+[n]) 
part3 // ([58, 49], [82, 76, 88, 90])



7 获取并解析XML Web服务




let xmlDoc = try? AEXMLDocument(xmlData: NSData(contentsOfURL: NSURL(string:"")!)!)

if let xmlDoc=xmlDoc {
    var prologue = xmlDoc.root.children[6]["PROLOGUE"]["SPEECH"]
    prologue.children[1].stringValue // Now all the youth of England are on fire,
    prologue.children[2].stringValue // And silken dalliance in the wardrobe lies:
    prologue.children[3].stringValue // Now thrive the armourers, and honour's thought
    prologue.children[4].stringValue // Reigns solely in the breast of every man:
    prologue.children[5].stringValue // They sell the pasture now to buy the horse,

8 在数组中查找最小(或最大)值

我们有各种方法来找到序列中的最小和最大值,其中有 minElement 和maxElement 函数:

//Find the minimum of an array of Ints
[10,-22,753,55,137,-1,-279,1034,77].reduce(Int.max, combine: min)

//Find the maximum of an array of Ints
[10,-22,753,55,137,-1,-279,1034,77].reduce(Int.min, combine: max)

9 并行处理



10 埃拉托斯特尼筛法




var n = 50
var primes = Set(2...n)

(2...Int(sqrt(Double(n)))).forEach{primes.subtractInPlace((2*$0).stride(through:n, by:$0))}

我们使用外部范围来迭代我们要检查的整数,并且对于每一个整数我们使用 stride(through:Int by:Int)计算出数字的倍数的序列。那些序列然后从Set中减去,Set用所有从2到n的整数初始化。



var sameprimes = Set(2...n)

						   .flatMap{ (2*$0).stride(through:n, by:$0)})




var a=1,b=2

(a,b) = (b,a)
a //2
b //1




over(order by salary) 按照salary排序进行累计,order by是个默认的开窗函数
over(partition by deptno)按照部门分区


   over(partition by deptno order by salary)


over(order by salary range between 5 preceding and 5 following):窗口范围为当前行数据幅度减5加5后的范围内的。



–sum(s)over(order by s range between 2 preceding and 2 following) 表示加2或2的范围内的求和

select name,class,s, sum(s)over(order by s range between 2 preceding and 2 following) mm from t2
adf        3        45        45  –45加2减2即43到47,但是s在这个范围内只有45
asdf       3        55        55
cfe        2        74        74
3dd        3        78        158 –78在76到80范围内有78,80,求和得158
fda        1        80        158
gds        2        92        92
ffd        1        95        190
dss        1        95        190
ddd        3        99        198
gf         3        99        198




over(order by salary rows between 5 preceding and 5 following):窗口范围为当前行前后各移动5行。



–sum(s)over(order by s rows between 2 preceding and 2 following)表示在上下两行之间的范围内
select name,class,s, sum(s)over(order by s rows between 2 preceding and 2 following) mm from t2
adf        3        45        174  (45+55+74=174)
asdf       3        55        252   (45+55+74+78=252)
cfe        2        74        332    (74+55+45+78+80=332)
3dd        3        78        379    (78+74+55+80+92=379)
fda        1        80        419
gds        2        92        440
ffd        1        95        461
dss        1        95        480
ddd        3        99        388
gf         3        99        293



over(order by salary range between unbounded preceding and unbounded following)或者

over(order by salary rows between unbounded preceding and unbounded following):窗口不做限制





cfe        2        74
dss        1        95
ffd        1        95
fda        1        80
gds        2        92
gf         3        99
ddd        3        99
adf        3        45
asdf       3        55
3dd        3        78

select * from
select name,class,s,rank()over(partition by class order by s desc) mm from t2
where mm=1;
dss        1        95        1
ffd        1        95        1
gds        2        92        1
gf         3        99        1
ddd        3        99        1

select * from
select name,class,s,row_number()over(partition by class order by s desc) mm from t2
where mm=1;
1        95        1  –95有两名但是只显示一个
2        92        1
3        99        1 –99有两名但也只显示一个

select name,class,s,rank()over(partition by class order by s desc) mm from t2
dss        1        95        1
ffd        1        95        1
fda        1        80        3 –直接就跳到了第三
gds        2        92        1
cfe        2        74        2
gf         3        99        1
ddd        3        99        1
3dd        3        78        3
asdf       3        55        4
adf        3        45        5
select name,class,s,dense_rank()over(partition by class order by s desc) mm from t2
dss        1        95        1
ffd        1        95        1
fda        1        80        2 –连续排序(仍为2)
gds        2        92        1
cfe        2        74        2
gf         3        99        1
ddd        3        99        1
3dd        3        78        2
asdf       3        55        3
adf        3        45        4

select name,class,s, sum(s)over(partition by class order by s desc) mm from t2 –根据班级进行分数求和
dss        1        95        190  –由于两个95都是第一名,所以累加时是两个第一名的相加
ffd        1        95        190
fda        1        80        270  –第一名加上第二名的
gds        2        92        92
cfe        2        74        166
gf         3        99        198
ddd        3        99        198
3dd        3        78        276
asdf       3        55        331
adf        3        45        376

first_value() over()和last_value() over()的使用   


SELECT opr_id,res_type,
first_value(res_type) over(PARTITION BY opr_id ORDER BY res_type) low,
last_value(res_type) over(PARTITION BY opr_id ORDER BY res_type rows BETWEEN unbounded preceding AND unbounded following) high
FROM rm_circuit_route
WHERE opr_id IN (‘000100190000000000021311′,’000100190000000000021355′,’000100190000000000021339’)
ORDER BY opr_id;

注:rows BETWEEN unbounded preceding AND unbounded following 的使用

–取last_value时不使用rows BETWEEN unbounded preceding AND unbounded following的结果


SELECT opr_id,res_type,
first_value(res_type) over(PARTITION BY opr_id ORDER BY res_type) low,
last_value(res_type) over(PARTITION BY opr_id ORDER BY res_type) high
FROM rm_circuit_route
WHERE opr_id IN (‘000100190000000000021311′,’000100190000000000021355′,’000100190000000000021339’)
ORDER BY opr_id;


rows BETWEEN unbounded preceding AND unbounded following,取出的last_value由于与res_type进行进行排列,因此取出的电路的最后一行记录的类型就不是按照电路的范围提取了,而是以res_type为范围进行提取了。






在first_value和last_value中ignore nulls的使用



取出该电路的第一条记录,加上ignore nulls后,如果第一条是判断的那个字段是空的,则默认取下一条,结果如下所示:

–lag() over()函数用法(取出前n行数据)
with a as
(select 1 id,’a’ name from dual
select 2 id,’b’ name from dual
select 3 id,’c’ name from dual
select 4 id,’d’ name from dual
select 5 id,’e’ name from dual
select id,name,lag(id,1,”)over(order by name) from a;

–lead() over()函数用法(取出后N行数据)

with a as
(select 1 id,’a’ name from dual
select 2 id,’b’ name from dual
select 3 id,’c’ name from dual
select 4 id,’d’ name from dual
select 5 id,’e’ name from dual
select id,name,lead(id,1,”)over(order by name) from a;

–ratio_to_report(a)函数用法 Ratio_to_report() 括号中就是分子,over() 括号中就是分母
with a as (select 1 a from dual
union all
select 1 a from dual
union  all
select 1 a from dual
union all
select 2 a from dual
union all
select 3 a from dual
union all
select 4 a from dual
union all
select 4 a from dual
union all
select 5 a from dual
select a, ratio_to_report(a)over(partition by a) b from a
order by a;

with a as (select 1 a from dual
union all
select 1 a from dual
union  all
select 1 a from dual
union all
select 2 a from dual
union all
select 3 a from dual
union all
select 4 a from dual
union all
select 4 a from dual
union all
select 5 a from dual
select a, ratio_to_report(a)over() b from a –分母缺省就是整个占比
order by a;

with a as (select 1 a from dual
union all
select 1 a from dual
union  all
select 1 a from dual
union all
select 2 a from dual
union all
select 3 a from dual
union all
select 4 a from dual
union all
select 4 a from dual
union all
select 5 a from dual
select a, ratio_to_report(a)over() b from a
group by a order by a;–分组后的占比


SELECT a.deptno,
(a.r-1)/(n-1) pr1,
percent_rank() over(PARTITION BY a.deptno ORDER BY a.sal) pr2
FROM (SELECT deptno,
rank() over(PARTITION BY deptno ORDER BY sal) r –计算出在组中的排名序号
FROM emp
ORDER BY deptno, sal) a,
(SELECT deptno, COUNT(1) n FROM emp GROUP BY deptno) b –按部门计算每个部门的所有成员数
WHERE a.deptno = b.deptno;

SELECT a.deptno,
(a.r + c.rn – 1) / n pr1,
cume_dist() over(PARTITION BY a.deptno ORDER BY a.sal) pr2
FROM (SELECT deptno,
rank() over(PARTITION BY deptno ORDER BY sal) r
FROM emp
ORDER BY deptno, sal) a,
(SELECT deptno, COUNT(1) n FROM emp GROUP BY deptno) b,
(SELECT deptno, r, COUNT(1) rn,sal
FROM (SELECT deptno,sal,
rank() over(PARTITION BY deptno ORDER BY sal) r
FROM emp)
GROUP BY deptno, r,sal
ORDER BY deptno) c –c表就是为了得到每个部门员工工资的一样的个数
WHERE a.deptno = b.deptno
AND a.deptno = c.deptno(+)
AND a.sal = c.sal;

SELECT ename,
percentile_cont(0.7) within GROUP(ORDER BY sal) over(PARTITION BY deptno) “Percentile_Cont”,
percent_rank() over(PARTITION BY deptno ORDER BY sal) “Percent_Rank”
FROM emp
WHERE deptno IN (30, 60);

SELECT ename,
percentile_cont(0.6) within GROUP(ORDER BY sal) over(PARTITION BY deptno) “Percentile_Cont”,
percent_rank() over(PARTITION BY deptno ORDER BY sal) “Percent_Rank”
FROM emp
WHERE deptno IN (30, 60);



SELECT ename,
percentile_disc(0.7) within GROUP(ORDER BY sal) over(PARTITION BY deptno) “Percentile_Disc”,
cume_dist() over(PARTITION BY deptno ORDER BY sal) “Cume_Dist”
FROM emp
WHERE deptno IN (30, 60);





来源: [选项] [目录名 | 列出相关目录下的所有目录和文件

<code>-a  列出包括.a开头的隐藏文件的所有文件
-A  通-a,但不列出"."和".."
-l  列出文件的详细信息
-c  根据ctime排序显示
-t  根据文件修改时间排序
---color[=WHEN] 用色彩辨别文件类型 WHEN 可以是'never'、'always'或'auto'其中之一
</code> [选项] 源文件或目录 目录或多个源文件 | 移动或重命名文件

<code>-b  覆盖前做备份
-f  如存在不询问而强制覆盖
-i  如存在则询问是否覆盖
-u  较新才覆盖
-t  将多个源文件移动到统一目录下,目录参数在前,文件参数在后
    mv a /tmp/ 将文件a移动到 /tmp目录下
    mv a b 将a命名为b
    mv /home/zenghao test1.txt test2.txt test3.txt

3.cp [选项] 源文件或目录 目录或多个源文件 | 将源文件复制至目标文件,或将多个源文件复制至目标目录。

<code>-r -R 递归复制该目录及其子目录内容
-p  连同档案属性一起复制过去
-f  不询问而强制复制
-s  生成快捷方式
-a  将档案的所有特性都一起复制

4.scp [参数] [原路径] [目标路径] | 在Linux服务器之间复制文件和目录

<code>-v  详细显示输出的具体情况
-r  递归复制整个目录
(1) 复制文件:  
scp local_file remote_username@remote_ip:remote_folder  
scp local_file remote_username@remote_ip:remote_file  
scp local_file remote_ip:remote_folder  
scp local_file remote_ip:remote_file  
(2) 复制目录:  
scp -r local_folder remote_username@remote_ip:remote_folder  
scp -r local_folder remote_ip:remote_folder  
    从 本地 复制到 远程
    scp /home/daisy/full.tar.gz root@ 
    从 远程 复制到 本地
    scp root@/ /home/daisy/full.tar.gz

5.rm [选项] 文件 | 删除文件

<code>-r  删除文件夹
-f  删除不提示
-i  删除提示
-v  详细显示进行步骤

6.touch [选项] 文件 | 创建空文件或更新文件时间

<code>-a  只修改存取时间
-m  值修改变动时间
-r  eg:touch -r a b ,使b的时间和a相同
-t  指定特定的时间 eg:touch -t 201211142234.50 log.log 
    -t time [[CC]YY]MMDDhhmm[.SS],C:年前两位

7.pwd 查看当前所在路径 改变当前目录

<code>- :返回上层目录
.. :返回上层目录
回车  :返回主目录
/   :根目录

9.mkdir [选项] 目录… | 创建新目录

<code>-p  递归创建目录,若父目录不存在则依次创建
-m  自定义创建目录的权限  eg:mkdir -m 777 hehe
-v  显示创建目录的详细信息

10.rmdir 删除空目录

<code>-v  显示执行过程
-p  若自父母删除后父目录为空则一并删除

11.rm [选项] 文件… | 一个或多个文件或目录

<code>-f  忽略不存在的文件,不给出提示
-i  交互式删除
-r  将列出的目录及其子目录递归删除
-v  列出详细信息


<code>-n  输出后不换行
-e  遇到转义字符特殊处理  
        echo "he\nhe"   显示he\nhe
        ehco -e "he\nhe"    显示he(换行了)he
</code> [选项] [文件]..| 一次显示整个文件或从键盘创建一个文件或将几个文件合并成一个文件

<code>-n  编号文件内容再输出
-E  在结束行提示$

14.tac | 反向显示

15.more | 按页查看文章内容,从前向后读取文件,因此在启动时就加载整个文件

<code>+n  从第n行开始显示
-n  每次查看n行数据
+/String    搜寻String字符串位置,从其前两行开始查看
-c  清屏再显示
-p  换页时清屏

16.less | 可前后移动地逐屏查看文章内容,在查看前不会加载整个文件

<code>-m  显示类似于more命令的百分比
-N  显示行号
/   字符串:向下搜索“字符串”的功能
?   字符串:向上搜索“字符串”的功能
n   重复前一个搜索(与 / 或 ? 有关)
N   反向重复前一个搜索(与 / 或 ? 有关)
b   向后翻一页
d   向后翻半页
</code> [选项]… [文件]… | 将输出内容自动加上行号
-b a 不论是否有空行,都列出行号(类似 cat -n)
-b t 空行则不列行号(默认)
-n 有ln rn rz三个参数,分别为再最左方显示,最右方显示不加0,最右方显示加0

18.head [参数]… [文件]… | 显示档案开头,默认开头10行

<code>-v  显示文件名
-c number   显示前number个字符,若number为负数,则显示除最后number个字符的所有内容
-number/n (+)number     显示前number行内容,
-n number   若number为负数,则显示除最后number行数据的所有内容

19.tail [必要参数] [选择参数] [文件] | 显示文件结尾内容

<code>-v  显示详细的处理信息
-q  不显示处理信息
-num/-n (-)num      显示最后num行内容
-n +num 从第num行开始显示后面的数据
-c  显示最后c个字符
-f  循环读取
</code> 编辑文件

<code>:w filename 将文章以指定的文件名保存起来  
:wq 保存并退出
:q! 不保存而强制退出
    按「i」切换进入插入模式「insert mode」,按"i"进入插入模式后是从光标当前位置开始输入文件;








21.which 可执行文件名称 | 查看可执行文件的位置,在PATH变量指定的路径中查看系统命令是否存在及其位置

22.whereis [-bmsu] [BMS 目录名 -f ] 文件名| 定位可执行文件、源代码文件、帮助文件在文件系统中的位置

<code>-b   定位可执行文件。
-m   定位帮助文件。
-s   定位源代码文件。
-u   搜索默认路径下除可执行文件、源代码文件、帮助文件以外的其它文件。
-B   指定搜索可执行文件的路径。
-M   指定搜索帮助文件的路径。
-S   指定搜索源代码文件的路径。

23.locate | 通过搜寻数据库快速搜寻档案

<code>-r  使用正规运算式做寻找的条件

24.find find [PATH] [option] [action] | 在文件树种查找文件,并作出相应的处理

1. 与时间有关的选项:共有 -atime, -ctime 与 -mtime 和-amin,-cmin与-mmin,以 -mtime 说明
    -mtime n :n 为数字,意义为在 n 天之前的『一天之内』被更动过内容的档案;
    -mtime +n :列出在 n 天之前(不含 n 天本身)被更动过内容的档案档名;
    -mtime -n :列出在 n 天之内(含 n 天本身)被更动过内容的档案档名。
    -newer file :file 为一个存在的档案,列出比 file 还要新的档案档名

2. 与使用者或组名有关的参数:
    -uid n :n 为数字,这个数字是用户的账号 ID,亦即 UID
    -gid n :n 为数字,这个数字是组名的 ID,亦即 GID
    -user name :name 为使用者账号名称!例如 dmtsai
    -group name:name 为组名,例如 users ;
    -nouser :寻找档案的拥有者不存在 /etc/passwd 的人!
    -nogroup :寻找档案的拥有群组不存在于 /etc/group 的档案!

3. 与档案权限及名称有关的参数:
    -name filename:搜寻文件名为 filename 的档案(可使用通配符)
    -size [+-]SIZE:搜寻比 SIZE 还要大(+)或小(-)的档案。这个 SIZE 的规格有:
        c: 代表 byte
        k: 代表 1024bytes。所以,要找比 50KB还要大的档案,就是『 -size +50k 』
    -type TYPE :搜寻档案的类型为 TYPE 的,类型主要有:
        一般正规档案 (f)
        装置档案 (b, c)
        目录 (d)
        连结档 (l)
        socket (s)
        FIFO (p)
    -perm mode :搜寻档案权限『刚好等于』 mode的档案,这个mode为类似chmod的属性值,举例来说,-rwsr-xr-x 的属性为4755!
    -perm -mode :搜寻档案权限『必须要全部囊括 mode 的权限』的档案,举例来说,
        我们要搜寻-rwxr--r-- 亦即 0744 的档案,使用-perm -0744,当一个档案的权限为 -rwsr-xr-x ,亦即 4755 时,也会被列出来,因为 -rwsr-xr-x 的属性已经囊括了 -rwxr--r-- 的属性了。
    -perm +mode :搜寻档案权限『包含任一 mode 的权限』的档案,举例来
        说,我们搜寻-rwxr-xr-x ,亦即 -perm +755 时,但一个文件属性为 -rw-------也会被列出来,因为他有 -rw.... 的属性存在!
4. 额外可进行的动作:
    -exec command :command 为其他指令,-exec 后面可再接额外的指令来处理搜寻到的结果。
    -print :将结果打印到屏幕上,这个动作是预设动作!
        find / -perm +7000 -exec ls -l {} \; ,额外指令以-exec开头,以\;结尾{}代替前面找到的内容
    | xargs 
        -i  默认的前面输出用{}代替 
            find . -name "*.log" | xargs -i mv {} test4

25.grep ‘正则表达式’ 文件名 | 用正则表达式搜索文本,并把匹配的行打印出来

<code>-c  只输出匹配行的计数。
-I  不区分大小写(只适用于单字符)。
-l  只显示文件名
-v  显示不包含匹配文本的所有行。
-n  显示匹配行数据及其行号

25.file | 判断文件类型

26.gzip [-cdtv#] 檔名 | 压缩、解压缩,源文件都不再存在

<code>-d  进行解压缩
-c  将压缩的数据输出到屏幕上
-v  :显示原档案/压缩文件案的压缩比等信息
-#  :压缩等级,-1最快,但压缩比最差,=9最慢,但压缩比最好

27.gunzip | 解压缩

28.bzip2 | 压缩、解压缩

<code>-d  :解压
-z  :压缩
-k  :保留源文件
-c :将压缩的过程产生的数据输出到屏幕上!
-v :可以显示出原档案/压缩文件案的压缩比等信息;
-# :与 gzip 同样的,都是在计算压缩比的参数, -9 最佳, -1 最快!

29.bzcat 读取数据而无需解压

30.tar [主选项+辅选项] 文件或者目录 | 多个目录或档案打包、压缩成一个大档案

    -c  建立打包档案,可搭配 -v 来察看过程中被打包的档名(filename)
    -t  察看打包档案的内容含有哪些档名,重点在察看『档名』就是了;
    -x  解打包或解压缩的功能,可以搭配 -C (大写) 在特定目录解开
    -j  透过 bzip2 的支持进行压缩/解压缩:此时档名最好为 *.tar.bz2
    -z  透过 gzip 的支持进行压缩/解压缩:此时档名最好为 *.tar.gz
    -v  在压缩/解压缩的过程中,将正在处理的文件名显示出来!
    -f filename -f 后面要立刻接要被处理的档名!
    -C 目录   这个选项用在解压缩,若要在特定目录解压缩,可以使用这个选项。
    --exclude FILE:在压缩打包过程中忽略某文件 eg: tar --exclude /home/zenghao -zcvf myfile.tar.gz /home/* /etc
    -p  保留备份数据的原本权限与属性,常用于备份(-c)重要的配置文件
    -P(大写)  保留绝对路径,亦即允许备份数据中含有根目录存在之意;
    压 缩:tar -jcvf filename.tar.bz2 要被压缩的档案或目录名称
    查 询:tar -jtvf filename.tar.bz2
    解压缩:tar -jxvf filename.tar.bz2 -C 欲解压缩的目录

31.exit 退出当前shell
32.logout 退出登录shell
33.shutdown -h now

34.users 显示当前登录系统地用户

35.who 登录在本机的用户与来源

<code>-H或--heading  显示各栏位的标题信息列。

36.w 登录在本机的用户及其运行的程序

<code>-s  使用简洁格式列表,不显示用户登入时间,终端机阶段作业和程序所耗费的CPU时间。
-h  不显示各栏位的标题信息列。

37.write 给当前联机的用户发消息

38.wall 给所有登录再本机的用户发消息

39.last 查看用户的登陆日志

40.lastlog 查看每个用户最后的登陆时间

41.finger [选项] [使用者] [用户@主机] | 查看用户信息

<code>-s 显示用户的注册名、实际姓名、终端名称、写状态、停滞时间、登录时间等信息
-l 除了用-s选项显示的信息外,还显示用户主目录、登录shell、邮件状态等信息,以及用户主目录下的.plan、.project和.forward文件的内容。
-p 除了不显示.plan文件和.project文件以外,与-l选项相同

42.hostname 查看主机名

43.alias ii = “ls -l” | 添加别名

44.unalias ii | 清除别名

45.useradd [-u UID] [-g 初始群组] [-G 次要群组] [-c 说明栏] [-d 家目录绝对路径] [-s shell] 使用者账号名 | 新增用户

<code>-M  不建立用户家目录!(系统账号默认值)
-m  建立用户家目录!(一般账号默认值)
-r  建立一个系统的账号,这个账号的 UID 会有限制 
-e  账号失效日期,格式为『YYYY-MM-DD』
-D  查看useradd的各项默认值

46.passwd | 修改密码

<code>-l  使密码失效
-u  与-l相对,用户解锁
-S  列出登陆用户passwd文件内的相关参数
-n  后面接天数,shadow 的第 4 字段,多久不可修改密码天数
-x  后面接天数,shadow 的第 5 字段,多久内必须要更动密码
-w  后面接天数,shadow 的第 6 字段,密码过期前的警告天数
-i  后面接『日期』,shadow 的第 7 字段,密码失效日期
使用管道刘设置密码:echo "zeng" | passwd --stdin zenghao

47.userdel 删除用户

<code>-r  用户文件一并删除

48.chage [-ldEImMW] 账号名 | 修改用户密码的相关属性

<code>-l  列出该账号的详细密码参数;
-d  后面接日期,修改 shadow 第三字段(最近一次更改密码的日期),格式YYYY-MM-DD
-E  后面接日期,修改 shadow 第八字段(账号失效日),格式 YYYY-MM-DD
-I  后面接天数,修改 shadow 第七字段(密码失效日期)
-m  后面接天数,修改 shadow 第四字段(密码最短保留天数)
-M  后面接天数,修改 shadow 第五字段(密码多久需要进行变更)
-W  后面接天数,修改 shadow 第六字段(密码过期前警告日期)

49.usermod [-cdegGlsuLU] username | 修改用户的相关属性

<code>-c  后面接账号的说明,即 /etc/passwd 第五栏的说明栏,可以加入一些账号的说明。
-d  后面接账号的家目录,即修改 /etc/passwd 的第六栏;
-e  后面接日期,格式是 YYYY-MM-DD 也就是在 /etc/shadow 内的第八个字段数据啦!
-f  后面接天数为 shadow 的第七字段。
-g  后面接初始群组,修改 /etc/passwd 的第四个字段,亦即是GID的字段!
-G  后面接次要群组,修改这个使用者能够支持的群组
-l  后面接账号名称。亦即是修改账号名称, /etc/passwd 的第一栏!
-s  后面接 Shell 的实际档案,例如 /bin/bash 或 /bin/csh 等等。
-u  后面接 UID 数字啦!即 /etc/passwd 第三栏的资料;
-L  冻结密码
-U  解冻密码
</code> [username] | 查看用户相关的id信息,还可以用来判断用户是否存在

51.groups 查看登陆用户支持的群组, 第一个输出的群组为有效群组

52.newgrp 切换有效群组

53.groupadd [-g gid] 组名 | 添加组

<code>-g  设定添加组的特定组id

54.groupmod [-g gid] [-n group_name] 群组名 | 修改组信息

<code>-g  修改既有的 GID 数字
-n  修改既有的组名

55.groupdel [groupname] | 删除群组

56.gpasswd | 群组管理员功能

    -gpasswd groupname 设定密码
    -gpasswd [-A user1,...] [-M user3,...] groupname
        -A  将 groupname 的主控权交由后面的使用者管理(该群组的管理员)
        -M  将某些账号加入这个群组当中
    -gpasswd [-r] groupname
        -r  将 groupname 的密码移除
    - gpasswd [-ad] user groupname 
        -a  将某位使用者加入到 groupname 这个群组当中
        -d  将某位使用者移除出 groupname 这个群组当中


58.mount [-t vfstype] [-o options] device dir

<code>-ro 采用只读方式挂接设备
-rw 采用读写方式挂接设备
eg:mount /home/mydisk.iso /tmp/mnt 通过mnt访问mydisk内的内容

59.umount 取消挂载


<code>-b :以字节为单位进行分割。这些字节位置将忽略多字节字符边界,除非也指定了 -n 标志。
-c :以字符为单位进行分割。
-d :自定义分隔符,默认为制表符。
-f  :与-d一起使用,指定显示哪个区域。


<code>-n   依照数值的大小排序。
-o&lt;输出文件&gt;   将排序后的结果存入指定的文件。
-r   以相反的顺序来排序。
-t&lt;分隔字符&gt;   指定排序时所用的栏位分隔字符。
-k  选择以哪个区间进行排序。

62.wc 统计指定文件中的字节数、字数、行数, 并将统计结果显示输出

<code>-l filename 报告行数
-c filename 报告字节数
-m filename 报告字符数
-w filename 报告单词数

63.uniq 去除文件中相邻的重复行

&> 正确、错误都重定向过去


64.set 显示环境变量和普通变量
65.env 显示环境变量
66.export 把普通变量变成环境变量
67.unset 删除一个环境变量

aaa(){} 定义函数

<code>-p  接提示字符
-t  接等待的秒数


<code>-i 声明为整数
-a 声明为数组
-f 声明为函数
-r 声明为只读

70.ulimit 限制使用者的某些系统资源

<code>-f  此 shell 可以建立的最大档案容量 (一般可能设定为 2GB)单位为 Kbytes eg: ulimit -f 1024 限制使用者仅能建立 1MBytes 以下的容量的档案

71.df [选项] [文件] | 显示指定磁盘文件的可用空间,如果没有文件名被指定,则所有当前被挂载的文件系统的可用空间将被显示

<code>-a  显示全部文件系统
-h  文件大小友好显示
-l  只显示本地文件系统
-i  显示inode信息
-T  显示文件系统类型

72.du [选项] [文件] | 显示每个文件和目录的磁盘使用空间

<code>-h  方便阅读的方式
-s  只显示总和的大小

73.ln [参数] [源文件或目录] [目标文件或目录] | 某一个文件在另外一个位置建立一个同步的链接

<code>-s  建立软连接   
-v  显示详细的处理过程

74.diff [参数] [文件1或目录1] [文件2或目录2] | 比较单个文件或者目录内容

<code>-b  不检查空格字符的不同。
-B  不检查空白行。
-i  不检查大小写
-q  仅显示差异而不显示详细信息
eg: diff a b &gt; parch.log 比较两个文件的不同并产生补丁
</code> [参数]… [+格式] | 显示或设定系统的日期与时间

<code>%H 小时(以00-23来表示)。 
%M 分钟(以00-59来表示)。 
%D 日期(含年月日)
%U 该年中的周数。
date -s “2015-10-17 01:01:01″ //时间设定
date +%Y%m%d         //显示前天年月日
date +%Y%m%d --date="+1 day/month/year"  //显示前一天/月/年的日期
date +%Y%m%d --date="-1 day/month/year"  //显示后一天/月/年的日期
date -d '2 weeks' 2周后的日期
</code> [参数] 月份] [年份] | 查看日历

<code>-1  显示当月的月历
-3  显示前、当、后一个月的日历
-m  显示星期一为一个星期的第一天
-s  (默认)星期天为第一天
-j  显示当月是一年中的第几天的日历
-y  显示当前年份的日历
</code> | 列出当前进程的快照

<code>a   显示所有的进程
-a  显示同一终端下的所有程序
e   显示环境变量
f   显示进程间的关系
-H  显示树状结构
r   显示当前终端的程序
T   显示当前终端的所有程序
-au 显示更详细的信息
-aux    显示所有包含其他使用者的行程 
-u  指定用户的所有进程
</code> [参数] | 显示当前系统正在执行的进程的相关信息,包括进程ID、内存占用率、CPU占用率等

79.kill [参数] [进程号] | 杀死进程 [参数] | 显示Linux系统中空闲的、已用的物理内存及swap内存,及被内核使用的buffer

81.vmstat | 对操作系统的虚拟内存、进程、CPU活动进行监控

82.iostat [参数] [时间t] [次数n](每隔t时间刷新一次,最多刷新n次)| 对系统的磁盘操作活动进行监视,汇报磁盘活动统计情况,同时也会汇报出CPU使用情况

<code>-p[磁盘] 显示磁盘和分区的情况
</code> [参数] [命令] |重复执行某一命令以观察变化

<code>-n  时隔多少秒刷新
-d  高亮显示动态变化
</code> [参数] [时间] | 在一个指定的时间执行一个指定任务,只能执行一次

<code>HH:MM[am|pm] + number [minutes|hours|days|weeks] 强制在某年某月某日的某时刻进行该项任务
atq 查看系统未执行的任务
atrm n 删除编号为n的任务
at -c n 显示编号为n的任务的内容

85.crontab | 定时任务调度

<code>file    载入crontab
-e  编辑某个用户的crontab文件内容
-l  显示某个用户的crontab文件内容
-r  删除某个用户的crontab文件

86.ifconfig [网络设备] [参数] | 查看和配置网络设备

87.route | 显示和操作IP路由表 [参数] [主机名或IP地址] | 测试与目标主机的连通性

<code>-q  只显示最后的结果

89.netstat | 显示与IP、TCP、UDP和ICMP协议相关的统计数据

90.telnet [参数] [主机] | 用于远程登录,采用明文传送报文,安全性不好

91.rcp [参数] [源文件] [目标文件] | 远程文件拷贝

<code>-r  递归复制
-p  保留源文件的属性
usage: rcp –r remote_hostname:remote_dir local_dir

92.wget [参数] [URL地址] | 直接从网络上下载文件

<code>-o FILE 把记录写到FILE文件中    eg : wget -O a.txt URL
wget --limit-rate=300k URL  限速下载


<code>-F 分隔符  以分隔符分隔内容
{}  要执行的脚本内容 eg:cat /etc/passwd |awk  -F ':'  '{print $1"\t"$7}'

94.sed 对数据行进行替换、删除、新增、选取等操作

<code>a   新增,在新的下一行出现
c   取代,取代 n1,n2 之间的行 eg: sed '1,2c Hi' ab
d   删除
i   插入,在新的上一行出现

95.paste 合并文件,需确保合并的两文件行数相同

<code>-d  指定不同于空格或tab键的域分隔符
-s  按行合并,单独一个文件为一行
</code> [参数] user | 切换登陆

<code>-l  切换时连同环境变量、工作目录一起改变
-c command  执行command变回原来的使用者

97.sudo | 以特定用户的权限执行特定命令

<code>-l  列出当前用户可执行的命令
-u username#uid 以指定用户执行命令