Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 在bash中的文件开头追加纪元日期_Regex_Bash - Fatal编程技术网

Regex 在bash中的文件开头追加纪元日期

Regex 在bash中的文件开头追加纪元日期,regex,bash,Regex,Bash,我有一个20个文件的列表,其中10个已经有1970-01-01-在名称的开头,10个没有(其余的都以一个小字母开头) 因此,我的任务是将那些开头没有纪元日期的文件也重命名为纪元日期。使用bash,下面的代码可以工作,但我无法使用正则表达式(例如使用rename)来解决它。我必须提取基本名称,然后再进一步。一个优雅的解决方案是只使用一个管道而不是两个 工作 因此,只需使用一个xargs或-exec?即可找到解决方案。您只需使用一个重命名命令: rename -n 's/^([a-z])/1970-

我有一个20个文件的列表,其中10个已经有1970-01-01-在名称的开头,10个没有(其余的都以一个小字母开头)

因此,我的任务是将那些开头没有纪元日期的文件也重命名为纪元日期。使用bash,下面的代码可以工作,但我无法使用正则表达式(例如使用rename)来解决它。我必须提取基本名称,然后再进一步。一个优雅的解决方案是只使用一个管道而不是两个

工作


因此,只需使用一个xargs或-exec?即可找到解决方案。

您只需使用一个
重命名
命令:

rename -n 's/^([a-z])/1970-01-01-$1/' *
假设您正在操作当前目录中的所有文件

请注意,
-n
标志(干运行)将仅通过
重命名
命令显示预期操作,但不会真正重命名任何文件

如果要与
find
结合使用,请使用:

find . -type f -maxdepth 1 -name '[a-z]*.txt' -execdir rename -n 's/^/1970-01-01-/' {} +

与短代码相比,我总是更喜欢可读代码

r() {
  base=$(basename "$1")
  dir=$(dirname "$1")
  if [[ "$base" =~ ^1970-01-01- ]]
  then
    : "ignore, already has correct prefix"
  else
    echo mv "$1" "$dir/1970-01-01-$base"
  fi
}
export -f r

find . -type f -exec bash -c 'r {}' \;
这也只是打印出将要做的事情(用于测试)。移除
mv
之前的
echo
,以获得真实的东西


请注意,
mv
将覆盖现有文件(如果已经有a./a/b/c和a./a/b/1970-01-01-c)。使用选项
-i
mv
可从此保存。

您是否尝试过
rename's/^([a-z])/1970-01-01-$1/'*.txt
哈哈,多么简单,我在find and exec循环中遇到了混乱。您仍然可以使用find and exec/xargs编辑您的答案吗?我只是想知道,我错在哪里。原因是,文件夹中有一些文件,比如1991-10-10-xyz.txt,也需要重命名为1970-01-01-xyz.txt。因此,我想先使用find命令提取需要的文件。使用
find
可以执行以下操作:
find-键入f-maxdepth 1-name'[a-z]*.txt'-execdir rename-n's/^/1970-01-01-/'{}+
,然后您可以调整这个
-name
选项或
rename
模式??但这是一个完全不同的问题。谢谢你的回答。
-name
不需要正则表达式。它采用的glob模式可能看起来像regex,但与regex非常不同。
r() {
  base=$(basename "$1")
  dir=$(dirname "$1")
  if [[ "$base" =~ ^1970-01-01- ]]
  then
    : "ignore, already has correct prefix"
  else
    echo mv "$1" "$dir/1970-01-01-$base"
  fi
}
export -f r

find . -type f -exec bash -c 'r {}' \;