shell脚本读写文件/case/二进制处理/循环/参数/字符分割等基本操作

目录

1.输入参数处理

1.1 $1~$9 加shift

1.2getopt

2.读写文件

2.1 读写文本文件

2.1.1读文本

2.1.2 写文本

2.2读写和显示二进制

2.2.1 写二进制

2.2.2 显示二进制

2.2.3 读二进制

3.字符串的分割 合并


1.输入参数处理

在shell中可以用$1~$9来get 参数超过9个参数需要用shift,也可以用read命令get参数,也可以用getopt解析参数。

如果要实现如下参数解析:

test.sh -i a.txt -o b.txt下面分情况说明

1.1 $1~$9 加shift

不用shift需要对 $1 $2分别判断,使用shift就只用$1

#!/bin/bash
echo $#
until [ $# -eq 0 ]
do
    case "$1" in
        -i|-input) 
            inputFile=$2
            shift 2
            ;;
        -o|-output) 
            outFile=$2
            shift 2
            ;;
        *) 
            shift
            echo "unknow para"
            ;;
    esac
done

echo "infile=$inputFile; outFile= $outFile"

以上同时给出了until do--done及case语句的语法

注意:1、*) 相当于其他语言中的default。

            2、各个分支中;;是必须的,;;相当于其他语言中的break

            3、 | 分割多个模式,相当于or

1.2getopt

可参考shell学习 - 处理脚本的多参数输入https://blog.csdn.net/czyt1988/article/details/79110450icon-default.png?t=LA92https://blog.csdn.net/czyt1988/article/details/79110450

2.读写文件

2.1 读写文本文件

可参考Linux Shell 脚本简单地读取,写入文件https://blog.csdn.net/weixin_44176696/article/details/105277306icon-default.png?t=LA92https://blog.csdn.net/weixin_44176696/article/details/105277306

2.1.1读文本

#!/bin/bash
while read line
do
    echo $line
done < filename#(待读取的文件)

或者使用cat命令。

for line in `cat filename`#(待读取的文件)
do
    echo $line
done

2.1.2 写文本

echo xxxxxx > test.log # >覆盖写 >>增加写
echo xxxxxx | tee test.log #覆盖写
echo xxxxxx | tee -a test.log #增加写

2.2读写和显示二进制

2.2.1 写二进制

echo 2a3f4d5c | xxd -r -ps > a.bin # 6 个字节

2.2.2 显示二进制

xxd a.bin
hd  a.bin
od -x a.bin
hexdump -x a.bin
hexdump -e '1/1 "%02x "' a.bin
hexdump -e '1/2 "%02x "' a.bin
hexdump -e '1/1 "%02x\n"' a.bin

分别的显示效果如下:

 

 由上图看出显示结果各不相同,可根据需要来采用不同的方式。

需要注意的是以下命令会将连续相同的数字用*表示

echo 2a2a2a2a | xxd -r -ps > a.bin # 6 个字节
hexdump -e '1/1 "%02x "' a.bin

 显示结果如下:

以上不同的格式 可以重定向到a.txt文件中形成对应的txt文件,在以TXT的文件方式去除最左边几列的地址(有的没有地址)和最右边乱码(有的没有乱码)顺序交换(2byte显示时高byte与低byte反了)

可以参考

Linux命令:hexdumphttps://www.cnblogs.com/klb561/p/11029440.htmlicon-default.png?t=LA92https://www.cnblogs.com/klb561/p/11029440.html

2.2.3 读二进制

需要使用dd 命令

还需要补充实例

可参考

shell 按字节读取文件https://blog.csdn.net/liuweichuan/article/details/7858317icon-default.png?t=LA92https://blog.csdn.net/liuweichuan/article/details/7858317

Linux dd 命令https://www.runoob.com/linux/linux-comm-dd.htmlicon-default.png?t=LA92https://www.runoob.com/linux/linux-comm-dd.html

3.字符串的分割 合并

可以完成

任意多个字符的合并

从任意位置截取任意长度字符

以指定分隔符分割字符串

可参考:

shell 字符串分割与连接https://www.cnblogs.com/gx-303841541/archive/2012/10/25/2738048.htmlicon-default.png?t=LA92https://www.cnblogs.com/gx-303841541/archive/2012/10/25/2738048.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值