shell字符串操作 正则表达式 读取终端和文件 特殊文件说明
- 2015-05-29 22:10:00
- admin
- 原创 2766
一、shell字符串操作
字符串拼接:直接拼接,不需要使用任何符号;
字符串长度:${#str}、expr length "$str"
字符串去除首尾空格:str=`echo "$str" | grep -oP "[^ \t]+([ \t]+[^ \t]+)*"`
字符串去除空格:str=`echo "$str" | sed "s/[ \t]//g"`
计算子串索引,索引从1开始,index支持字符串查找,match支持正则表达式查找:
echo "this is string" | awk '{printf("%d\n",index($0,"is"))}'
echo "this is string" | awk '{printf("%d\n",match($0,"is"))}'
取变量子串:
${var:off:len},索引从0开始,长度不写表示取到字符串末尾,${file:0:5}提取最左边的5个字节;
expr substr "goodnight" 1 4,substr STRING POS LENGTH,索引从1开始;
取变量子串,#去掉左边,%去掉右边:
file=/dir1/dir2/file.txt.txt
${file#*/},拿掉第一个/及其左边的字符串,结果dir1/dir2/file.txt.txt
${file##*/},拿掉最后一个/及其左边的字符串,结果file.txt.txt
${file%.*},拿掉最后一个.及其右边的字符串,结果/dir1/dir2/file.txt
${file%%.*},拿掉第一个.及其右边的字符串,结果/dir1/dir2/file
变量内容替换:
${file/dir/path},将第一个dir替换为path,结果/path1/dir2/file.txt.txt
${file//dir/path},将全部dir替换为path,结果/path1/path2/file.txt.txt
二、shell正则表达式
1、Bash3.0开始内置正则表达式,BASH_REMATCH变量存储匹配结果;
2、字符串包含正则表达式时,整个表达式返回真;
3、点符号匹配任意字符;
[[ "i am feinen" =~ [a-z\ ]*(feinen) ]]
echo ${BASH_REMATCH[*]} 输出i am feinen feinen
[[ "i am feinen" =~ .*(feinen) ]]
echo ${BASH_REMATCH[*]} 输出i am feinen feinen
[[ "i am feinen" =~ (feinen) ]]
echo ${BASH_REMATCH[*]} 输出feinen feinen
三、读取终端和文件
读取标准输入:
echo -n "Enter your name: "
read name
read -p "Enter your name: " name
默读标准输入:read -s password
读取文件内容:var=$(<file),忽略文件最后一个换行;
从文件逐行读取数据,如果最后一行没有换行符,则最后一行无法读出。
方法1:
while read myline
do
echo $myline
done <file
方法2:
cat file | while read myline
do
echo $myline
done
四、linux特殊文件说明
/dev/null,空设备是特殊的设备文件,丢弃一切写入其中的数据,读取它则会立即得到一个EOF。
丢弃控制台输出:
>/dev/null 2>&1
1>/dev/null 2>&1
1>/dev/null 2>/dev/null
清空文件内容:
cat /dev/null >main.txt
>main.txt
/dev/zero,读它的时候提供无限空字符(NULL, ASCII NUL, 0x00),写入它的数据丢失不见。
/dev/zero主要用来创建指定长度的空文件,比如临时交换文件:
dd if=/dev/zero of=main.cpp bs=4M count=1,复制4M的内容;
dd if=/dev/zero of=main.cpp bs=512K count=1,复制512K的内容;
dd用于复制和转换文件,具有cp的功能,但比cp更强大,常用参数:
1、bs,read and write BYTES bytes at a time
2、if,read from FILE instead of stdin
3、of,write to FILE instead of stdout
4、单位包括:c=1、K=1024、M=1024*1024