【问题标题】:searching for part of a filename (UNIX)搜索文件名的一部分 (UNIX)
【发布时间】:2013-10-10 06:56:15
【问题描述】:

在 unix 上,我的文件已重命名为原始名称,后跟 _inode 编号(即文件 dog 将重命名为 dog_inodeno)。我现在正在尝试删除 inode no,以便我可以在其他地方搜索原始文件名。有谁知道我该怎么做以及需要编码。

谢谢

【问题讨论】:

  • 我想重命名文件的脚本可以稍作修改以重命名这些文件。没有?

标签: unix search cut inode


【解决方案1】:

这应该可以完成工作:

find . -type f -name "*_[0-9]*" -exec \
  sh -c 'for i do
    b=$(basename "$i")
    r=$(basename "$i" "_$(ls -i "$i"|awk "{print \$1}")")
    if [ "$b" != "$r" ]; then 
      echo mv "$i" "$(dirname $i)/$r"
    fi
  done' sh {} + 

echo mv 替换为 mv 以使脚本实际重命名文件。

【讨论】:

  • 基本上我所有的文件名都是格式化的 filename_inodeno,我想创建一个脚本来剪切包括_和之后的所有内容。
  • 这正是我建议的脚本正在做的,不是吗?
【解决方案2】:

仅当文件的 inode 编号是上述格式的文件名的一部分时,此处的解决方案才会重命名您的文件,这是 OP 想要的。

解决方案在我的最后测试成功。

find ./ -name "*_[0-9][0-9][0-9][0-9][0-9][0-9]" -exec sh 'rename-files.sh' {} \;

存储下面的脚本以使查找命令成功。

#Script Name: rename-files.sh
#!/bin/bash

#Store the result of find
find_result=$1

#Get the existing file name
fname_alone=`expr ${find_result} : '.*/\(.*\)' '|' ${find_result}`
fname_with_relative_path=`expr ${find_result} : '.\(.*\)' '|' ${find_result}`
fname_with_full_path=`echo "$(pwd)${fname_with_relative_path}"`

#Get the inode number of file name
file_inode_no=`find ./ -name ${fname_alone} -printf '%i'`

#Read the end of name
end_of_name=`echo $fname_alone | awk -F "_" '{print $NF}' ` 

#Check if end of name contains its file's inode number
if [ $end_of_name -eq $file_inode_no ]
then
   #Remove the inode number at the end of file name 
   new_name=`expr $find_result : '.\(.*\)_.*' '|' $find_result`
   #Append the path of the file
   renamed_to=`echo "$(pwd)${new_name}"` 
   #Rename your dog_inodeno to dog
   mv $fname_with_full_path $renamed_to
fi

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    相关资源
    最近更新 更多