码迷,mamicode.com
首页 > 系统相关 > 详细

shell实战:多种方式实现获取列内容

时间:2017-04-09 21:30:25      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:linux

自己不是专业的linux,平时工作中也不用linux编程,自学一些linux shell编程,忘了学,学了忘,效率不高。今天权当复习吧。

想想这样一个情景吧,获取某一行的部分列值。

考虑这样的输入:“root:x:0:0:root:/root:/bin/bash”,现在我们获取用户及shell信息。自己暂时想到的5种实现方式。

#!/bin/bash
##############################################
#第二种实现 普通循环
##############################################
line="root:x:0:0:root:/root:/bin/bash";
oldIFS=$IFS;
IFS=":";
declare -i count=0;
#count=0;
for item in $line; 
do
	[ $count -eq 0 ] && user=$item
	if [[ $count -eq 6 ]]; then
		shell=$item
	fi
	#let count++
	count=$[ $count+1 ]
	#count=$(($count+1))
	#count=`expr $count+1`
	#count=$(expr $count+1);
done
IFS=$oldIFS;
echo 1: $user\‘s shell is  $shell by process:$$;
##############################################
#第二种实现 借助sed命令;
##############################################
user=`echo $line |sed ‘s/:.*$//‘`;
shell=$(echo $line |sed ‘s/^.*://‘);
echo 2: $user\‘s shell is  $shell by process:$$;
##############################################
#第3种实现 借助cut命令;
##############################################
user=`echo $line |cut -d: -f1`;
shell=$(echo $line |cut -d: -f7);
echo 3: $user\‘s shell is  $shell by process:$$;

##############################################
#第4种实现  xargs使用
#############################################
echo $line |xargs -d: -n 1 |tr -s ‘\n‘> file4
user=`cat  file4 | head -n 1`
shell=`cat file4 | tail -n 1`;
echo 4: $user\‘s shell is  $shell by process:$$;
rm -rf file4 2>>/dev/null
##############################################
#第5种实现  awk使用
#############################################
 echo $line |awk  -F ‘:‘  ‘{print "5:" $1 " ‘\‘‘s "  " shell is" $7 }‘

分析:抛开5种方式的优劣。可以了解以下内容。

  1. 文本处理工具:sed,tr

  2. 文本列选择工具:cut,awk

  3. 文本行选择工具:head,tail

  4. 计数运算多种方式:$[],$(()),``

  5. 变量声明:declare

  6. 参数处理:xargs


其实,在编写过程,连自己经常使用的命令,自己都记不起来。看来会和熟练还是不一样的。

本文出自 “简单” 博客,请务必保留此出处http://dba10g.blog.51cto.com/764602/1914312

shell实战:多种方式实现获取列内容

标签:linux

原文地址:http://dba10g.blog.51cto.com/764602/1914312

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!