Search code examples
awksedfile-rename

rename files: delete name up to first underscore


I have several thousand files that need to be renamed. They are in the form of xxxxx_file name.doc

The xxxx is alpha-numeric but in all cases the prefix upto and including the first underscore needs to be removed if possible. There will be some files that will end up with duplicate names so it is important that any duplicates don't overwrite an existing file (they should be ignored).

If there is no underscore, it should be skipped.

examples:
3445sh0_may_receipts.doc
df784hb68_sample.file-name.doc
b6890zs22_sample file name.doc
b6890zs22_sample_name.doc
gh7856n77.doc
56n57swd0.doc
etc ...

I am not skilled in the use of awk, but it seems that awk might be used with the underscore as a delimiter and the first column up to the first underscore ignored. I don't know what awk would do if a duplicate file is found.


Solution

  • improving on @dawg's anser

    for fn in *_*; do
        if [[ ! -f "${fn#*_}" ]]
        then 
           mv -i "$fn" "${fn#*_}"
        fi
    done 
    

    don't move if the file exists, and as an additional protection, prompt for overwrite.