从bash中的输入文件生成输出文件名 [英] Generating the output file name from the input file in bash

查看:205
本文介绍了从bash中的输入文件生成输出文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个bash脚本:

I have a bash script:

#!/bin/bash
convert "$1" -resize 50% "$2"

不是在脚本运行时传递两个参数,我只想提及源代码(或输入文件名)和输出文件名应从源文件名自动生成。像这样的 $ 1 | cut -d’。’-f1 .jpg 。如果输入文件名为 myimage.png ,则输出名称应为 myimage.jpg .jpg 应该附加到源文件名的第一部分。如果参数为: *。png ,它也应该起作用。那么如何修改脚本?

Instead of passing two arguments while the script is run I want to mention just the source (or input file name) and the output file name should be auto-genarated from the source file name. Something like this "$1" | cut -d'.' -f1".jpg". If the input file name was myimage.png, the output name should be myimage.jpg. .jpg should be appended to the fist part of the source file name. It should also work if the argument is: *.png. So how can I modify my script?

推荐答案

扩展 $ {X%pattern} 删除$ X末尾的模式

The expansion ${X%pattern} removes pattern of the end of $X.

convert "$1" -resize 50% "${1%.*}.jpg"

上班在多个文件上:

for filename ; do
    convert "$filename" -resize 50% "${filename%.*}.jpg"
done

这将迭代每个命令行参数,并且是的缩写,表示 $ @ 中的文件名。您不必担心检查参数是否为 *。png -Shell将为您扩展该参数-您将简单地收到扩展的文件名列表。

This will iterate over each of the command line arguments and is shorthand for for filename in "$@". You do not need to worry about checking whether the argument is *.png - the shell will expand that for you - you will simple receive the expanded list of filenames.

这篇关于从bash中的输入文件生成输出文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆