`

shell脚本学习指南笔记-3.查找与替换

 
阅读更多

root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin

 

$ cut -d / -f 1,2 /etc/passwd

 

root:x:0:0:root:/root:
bin:x:1:1:bin:/bin:
daemon:x:2:2:daemon:/sbin:

 

root     pts/0        2011-11-16 06:49 (192.168.1.100)

 

$ who | cut -d / -f 1

 

root     pts

 

$ ls -l | cut -c 1-10

total 16
drwxr-xr-x
-rw-r--r--
-rw-r--r--

 

cut -c list [file]

cut -f list [-d delim] [file]

 

-c list  查询每行的list所表示数据索引的数据   list如:1,10 or 1-10

-d delim   根据delim为定界符,默认为Tab

-f  list   设置list的数据段索引,根据-d  返回对应的数据

注:在centos5.4中测试,无法单独的使用-d,一定要和-f一起使用

 

 

 

 

 

JOIN的用法

 

 

quotas

 

joe    50
jane   75
herman 80
chris  95
 

 

sales

 

joe    100
jane   200
herman 150
chris  300
 
#! /bin/sh

#删除注释
sed '/^#/d' quotas | sort > quotas.sorted
sed '/^#/d' sales  | sort > sales.sorted

#连接两个文本且打印
join quotas.sorted sales.sorted

#删除缓存文件
rm quotas.sorted sales.sorted

 

 

sed的简单用法

 

#s命令,要求用正则表达式进行寻找,/为分格符,且是默认的分格符,此命令是把baidu替换为google
echo www.baidu.com | sed 's/baidu/google/'
结果:www.google.com

# ; 为分格符,这里是自定义的分格符,紧跟s后的字符,都被认为新的分格符
echo /home/tolstoy | sed 's;\(/home\)/tolstoy;\1/lt;'

# 寻找192.168.0.1开头行,且在192.168.0.1后追加localhost字符串
echo 192.168.0.1:8080 | sed 's/^192.168.0.1/&localhost/'

# 寻找192.168.0.1开头行,且在192.168.0.1替换为localhost字符串
echo 192.168.0.1:8080 | sed 's/^192.168.0.1/localhost/'

cat > template-date
192.168.0.1
what is your name?
what is this?
loveable
I love you
I like you
I need you
^d

# -n与p一起使用,将只打印已被替换的行
sed -n 's/\(love\)able/\1rs/p' template-date

# 打印第1行到第一个以I开头的行的所有行
sed -n '1,/^I/p' template-date

# 从192到I的所有行,每行结束更换为sed test,且打印
sed -n '/192/,/I/s/$/sed test/p' template-date
192.168.0.1sed test
what is your name?sed test
what is this?sed test
loveablesed test
I love yoused test
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics