Removing last n characters from Unix Filename before the extension

北慕城南 提交于 2019-12-11 23:04:33

问题


I have a bunch of files in Unix Directory :

  test_XXXXX.txt  
  best_YYY.txt   
  nest_ZZZZZZZZZ.txt

I need to rename these files as

  test.txt   
  best.txt   
  nest.txt

I am using Ksh on AIX .Please let me know how i can accomplish the above using a Single command .

Thanks,


回答1:


In this case, it seems you have an _ to start every section you want to remove. If that's the case, then this ought to work:

for f in *.txt
do
  g="${f%%_*}.txt"
  echo mv "${f}" "${g}"
done

Remove the echo if the output seems correct, or replace the last line with done | ksh.

If the files aren't all .txt files, this is a little more general:

for f in *
do
  ext="${f##*.}"
  g="${f%%_*}.${ext}"
  echo mv "${f}" "${g}"
done



回答2:


If this is a one time (or not very often) occasion, I would create a script with

$ ls > rename.sh
$ vi rename.sh
:%s/\(.*\)/mv \1 \1/
(edit manually to remove all the XXXXX from the second file names)
:x
$ source rename.sh

If this need occurs frequently, I would need more insight into what XXXXX, YYY, and ZZZZZZZZZZZ are.


Addendum

Modify this to your liking:

ls | sed "{s/\(.*\)\(............\)\.txt$/mv \1\2.txt \1.txt/}" | sh

It transforms filenames by omitting 12 characters before .txt and passing the resulting mv command to a shell.

Beware: If there are non-matching filenames, it executes the filename—and not a mv command. I omitted a way to select only matching filenames.



来源:https://stackoverflow.com/questions/17601353/removing-last-n-characters-from-unix-filename-before-the-extension

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!