Shell优化操作

Undefined 深圳 2018/04/08

1.常用语句

用rm递归递归删除子目录下所有.o后缀文件

find . -name "*.o"  | xargs rm -f

eval赋值


echo "$info" | while read mch_id ;do
	if [[ ${#mch_id} -eq 15 ]];then
		# echo "修改用户 $mch_id 的状态"
		eval $(echo $mch_id | awk '{mn=$1%100;m=mn/10;n=mn%10;printf("m=%d;n=%d", m, n);}')
		sql1="update trade.t_mch_$m$n set F_cert_audit = 1 where f_Mch_id = '$mch_id'  limit 1 "
		echo ${sql1}
		if [ $real_update -eq 1 ] ;then 
			$sql_cmd -e "$sql1"
		fi  
	fi  
done 

列加上单引号,多行变成1行

cat source.txt  | awk '{print "'\''"$1"'\','"}' | sed ':a;N;$!ba;s/\n/ /g'

awk '{print "'\''"$1"'\','"}' //第一列前加上单引号,后面加上单引号逗号
sed ':a;N;$!ba;s/\n/ /g'     //多行变成1行


注意是空格(0x20)还是tab(0x09)键

[Tool]# cat test.log 
1, ,2
3,	,4
[Tool]# cat test.log  | xxd
0000000: 312c 202c 320a 332c 092c 340a            1, ,2.3,.,4.
[Tool]# sed 's/, ,/,/g' test.log 
1,2
3,	,4
[Tool]# sed 's/,\t,/,/g' test.log 
1, ,2
3,4

sort 排序

sort test1.txt > text2.txt (要两个文件)
	-k 按照第一列来排序,默认第一列

join两个文件(需要先排序)

join中 -a 1 相当于left join  
	   -a 2 相当于right join
	   -j 1 都拿出第一列来对比
	   join 1.txt 2.txt (相当于默认加上 -j 1)
	   如果两个文件是不同列。那么可以直接 -1 1 -2 4 
	   相当于第一个文件第一列,跟第二个文件第4列对比(先排序)
[Tool]# cat test.log 
1, ,2
3,	,4
[Tool]# cat test2.log 
1,我是文件2
2,我是文件2
3,我是文件2
[Tool]# join -a 1 test.log  test2.log 
1, ,2
3, ,4
[Tool]# join -a 1  -t , test.log  test2.log 
1, ,2,我是文件2
3,	,4,我是文件2
[Tool]# vim test3.log
[Tool]# cat test3.log 
3,我是文件3
1,我是文件3
[Tool]# join -a 1  -t , test.log  test3.log 
1, ,2
join: 文件2 没有被正确排序
3,	,4,我是文件3
[Tool]# sort test3.log  > test3.log  //这里还直接清空了test3.log文件
[Tool]# join -a 1  -t , test.log  test3.log 
1, ,2
3,	,4
[Tool]# cat test3.log 
[Tool]# vim test3.log  //再把源文件完整
[Tool]# sort test3.log  > test4.log 
[Tool]# join -a 1  -t , test.log  test4.log 
1, ,2,我是文件3
3,	,4,我是文件3

去掉末尾的最后一个字符

[Tool]# cat test4.log 
1,我是文件3,
3,我是文件3,
[Tool]# sed 's/.$//' test4.log 
1,我是文件3
3,我是文件3
[Tool]# vim test4.log 
[Tool]# cat test4.log  |xxd 
0000000: 312c e688 91e6 98af e696 87e4 bbb6 332c  1,............3,
0000010: 0920 0a33 2ce6 8891 e698 afe6 9687 e4bb  . .3,...........
0000020: b633 2c09 0a                             .3,..
[Tool]# sed 's/.$//' test4.log  //依然无效,因为后面的字符不是元字符
1,我是文件3,	
3,我是文件3,
[Tool]# cat test4.log  |xxd  //可以看到最后是09(tab) 0a(空格)
0000000: 312c e688 91e6 98af e696 87e4 bbb6 332c  1,............3,
0000010: 0920 0a33 2ce6 8891 e698 afe6 9687 e4bb  . .3,...........
0000020: b633 2c09 0a                             .3,..
[Tool]# cat test4.log  |awk -F ',' '{print $1","$2}'
1,我是文件3
3,我是文件3

awk 显示逗号在结果中

 cat test4.log  |awk -F ',' '{print $1","$2}'

多文件合并到一个文件

cat test1.log test2.log  test3.log > test4.log


扫描关注我

(转载本站文章请注明作者和出处 Undefined

Post Directory