• 【shell基础】替换后缀名复制同名文件


    script

    # copy images with same name as json file to one directory
    dir=/home/xxx/output_tfl_20220630
    mkdir $dir/image
    for file in $dir/*.json; do
        # echo $file
        pngname=${file/%.json/.png} # OK
    newname=${file%.json}.png # OK cp
    $pngname $dir/image # echo $pngname done

     解析

    脚本最重要的部分是

    pngname=${file/%.json/.png}

    这部分的含义就是将字符串file的.json后缀替换成.png,还有一种写法就是匹配删除,然后在大括号后面加上要替换成的部分,

    newname=${file%.json}.png

    如:${file%.json}.png,这个就是将字符串的.json后缀修改为.png。

    两种方法都可以的。

    注意,后来发现复制的文件有可能会发生变化,比如复制一张图像,原图像是正常的,1.5M大小,复制之后发现文件内容有损坏,大小是1.2M。

    update 20220801

    如果目录不一样,但是文件名需要一致呢?

    basename: 该命令的作用是从路径中提取出文件名,使用方法为basename NAME [SUFFIX]

    dirname: 该命令的作用是从路径中提取出目录名,使用方法为 dirname NAME

    dir=/e/04_Dataset/traffic_light/annotation
    # mkdir $dir/image
    for file in $dir/tfl_anno/*.json; do
        echo $file
        dirn=$(dirname $file)
        base=$(basename $file)
        echo $dirn
        echo $base
    done

    output:

    /e/04_Dataset/traffic_light/annotation/tfl_anno/TFL_00010_20220726T132451.json
    /e/04_Dataset/traffic_light/annotation/tfl_anno
    TFL_00010_20220726T132451.json

    update20220826

    将imagedis文件中每一行的字符串images和png分别替换为labels、txt;script.sh内容如下:

    #! bin/bash
    imagedis=/media/xxx/dataset/traffic_light/image_dis.txt
    labeldis=/media/xxx/dataset/traffic_light//label_dis.txt
    # lines=$(cat image)
    rm $labeldis
    for line in `cat $imagedis`
    do
        newname=${line%.png}.txt
        echo $newname
        # newname=${line/%images/labels}
        newname=${newname/images/labels}
        echo $newname
        echo $newname >>$labeldis # append 
        # echo $newname > $labeldis  # overide
    done

    出现错误

    bad substitution

    发现只要在运行的时候使用bash script.sh即可;

    参考

    1. shell获取文件名和文件目录

  • 相关阅读:
    Mybatis学习01:利用mybatis查询数据库
    SpringBoot_登录注册
    python抓取中科院大学招聘
    centos7设置固定IP
    PIL给图片加水印
    You can ignore those files in your build.gradle
    mysql事件执行时间
    wampserver2.5域名解析错误问题
    Mysql错误消息 语言设置
    js控制select多选
  • 原文地址:https://www.cnblogs.com/happyamyhope/p/16446828.html
Copyright © 2020-2023  润新知