使用 sed 更改文件扩展名 [英] Changing file extensions with sed

查看:50
本文介绍了使用 sed 更改文件扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果参数是文件,我想将它们的扩展名更改为 .file.

这就是我得到的:

#!/bin/bash而 [ $# -gt 0 ]做如果 [ -f $1 ]然后sed -i -e "s/\(.*\)\(\.\)\(.*\)/\1\2file" $1菲转移完毕

脚本正在运行,但它什么也没做.另一个问题是文件没有任何扩展名,我的 sed 命令不起作用,对吗?请帮忙.

解决方案

sed 用于操作文件的内容,而不是文件名本身.

选项 1,取自 John Smith 的回答:

<块引用>

filename="file.ext1"mv "${filename}" "${filename/%ext1/ext2}"

选项 2,取自 chooban 的这个答案:

<块引用>

rename 's/\.ext/\.newext/' ./*.ext

选项 3,取自 David W. 的回答:

<块引用>

$ 查找.-name "*.ext1" -print0 |同时读取 -d $'\0' 文件做mv $file "${file%.*}.ext2"完毕

更多内容在这里.

更新:(评论中询问 % 和 {} 在做什么?)

"${variable}othter_chars" > 如果你想在字符串中扩展一个变量,你可以使用它.和 %.*{} 表示从值的尾部从模式 .* 中取出变量的值,例如,如果您variable be filename.txt "${variable%.*} 只返回 filename.

If the arguments are files, I want to change their extensions to .file.

That's what I got:

#!/bin/bash

while [ $# -gt 0 ]
do
    if [ -f $1 ]
    then
       sed -i -e "s/\(.*\)\(\.\)\(.*\)/\1\2file" $1

    fi
    shift
done

The script is running, but it doesn't do anything. Another problem is that file hasn't any extension, my sed command will not work, right? Please help.

解决方案

sed is for manipulating the contents of files, not the filename itself.

Option 1, taken from this answer by John Smith:

filename="file.ext1"
mv "${filename}" "${filename/%ext1/ext2}"

Option 2, taken from this answer by chooban:

rename 's/\.ext/\.newext/' ./*.ext

Option 3, taken from this answer by David W.:

$ find . -name "*.ext1" -print0 | while read -d $'\0' file
do
   mv $file "${file%.*}.ext2"
done

and more is here.

UPDATE : (in comment asked what % and {} doing?)

"${variable}othter_chars" > if you want expand a variable in string you can use it. and %.* in {} means take the value of variable strip off the pattern .* from the tail of the value for example if your variable be filename.txt "${variable%.*} return just filename.

这篇关于使用 sed 更改文件扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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