【问题标题】:Removing the file extension in a text file bash [duplicate]删除文本文件bash中的文件扩展名[重复]
【发布时间】:2023-04-07 00:56:02
【问题描述】:

所以我在一个文本文件中放了很多文件名,这些文件具体是.log 文件:

ls *.log > finished_data.txt

现在我有了.log 文件的列表,如何保留名称但删除.log 扩展名? 我的思维过程正在重命名它们?

【问题讨论】:

  • 你有没有注意到这个页面右上角的Search Q&A框?

标签: linux bash


【解决方案1】:

只需遍历.log 文件并移动它们:

for file in *.log
do
    mv "$file" "${file%.log}"
done

这使用shell parameter expansion:

$ d="a.log.log"
$ echo "${d%.log}"
a.log

【讨论】:

  • 谢谢你,完美的工作我怎么能扭转行动?说在某些文件的末尾添加 .log?
  • @user3667111 就说mv "$file" "${file}.log"
  • @gniourf_gniourf 哦,谢谢,我总是对%%% 感到困惑。我看到% 去掉了最短的匹配,这是最准确的。关于for循环的语法:有什么区别吗?
  • @gniourf_gniourf 啊,真的!我误解了您的评论,并认为您指的是使用 for file in ...; do 而不是 for file in ... + new line + do。你是绝对正确的,更新。
【解决方案2】:

使用rename 重命名所有.log 文件,方法是从末尾删除.log

rename 's/\.log$//' *.log
  • \.log$ 与文件名末尾的 .log 匹配,并通过替换为空白来省略

如果您使用的是prename,那么您可以先进行试运行:

rename -n 's/\.log$//' *.log

如果对所做的更改感到满意:

rename 's/\.log$//' *.log

【讨论】:

    猜你喜欢
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    相关资源
    最近更新 更多