如何使用bash和sed操作文件名?

Mar*_*ark 5 bash shell sed

我试图遍历目录中的所有文件.

我想在每个文件上做一些事情(将其转换为xml,不包括在示例中),然后将文件写入新的目录结构.

for file in `find /home/devel/stuff/static/ -iname "*.pdf"`;
do
  echo $file;
  sed -e 's/static/changethis/' $file > newfile +".xml";
  echo $newfile;
done
Run Code Online (Sandbox Code Playgroud)

我希望结果如下:

$ file => /home/devel/stuff/static/2002/hello.txt

$ newfile => /home/devel/stuff/changethis/2002/hello.txt.xml

我该如何改变我的sed线?

Mic*_*jer 5

如果你需要重命名多个文件,我建议使用rename命令:

# remove "-n" after you verify it is what you need
rename -n 's/hello/hi/g' $(find /home/devel/stuff/static/ -type f)
Run Code Online (Sandbox Code Playgroud)

或者,如果你没有rename尝试这个:

find /home/devel/stuff/static/ -type f | while read FILE
do
    # modify line below to do what you need, then remove leading "echo" 
    echo mv $FILE $(echo $FILE | sed 's/hello/hi/g')
done
Run Code Online (Sandbox Code Playgroud)


Mu *_*iao 4

您是否正在尝试更改文件名?然后

for file in /home/devel/stuff/static/*/*.txt
do
    echo "Moving $file"
    mv "$file" "${file/static/changethis}.xml"
done
Run Code Online (Sandbox Code Playgroud)

/home/devel/stuff/static/*/*.txt在使用脚本之前请确保这是您想要的。