Find the answer to your Linux question:
Results 1 to 2 of 2
Hi all !! I have to rename all txt files in a directory to their first word. I am running the following command: for FILE in *.txt; do FW=$(head -1 ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Mar 2012
    Posts
    11

    Renaming a directory's txt files to their first word


    Hi all !!

    I have to rename all txt files in a directory to their first word. I am running the following command:

    for FILE in *.txt;
    do FW=$(head -1 $FILE|awk '{printf $1}');
    mv $FILE $FW.txt;
    done

    The problem is that if the directory already has a file whose name is it's first word, the command fails and cannot rename files after that file.

    Is there a better way to do this? Or is there an option to make mv ignore the error if file names are same? (I couldn't find one in the man pages, the -f or --force doesn't help)

    Thank you in advance !!

  2. #2
    Linux Engineer Kloschüssel's Avatar
    Join Date
    Oct 2005
    Location
    Italy
    Posts
    773
    I think this is what you could do:

    bash file test operators


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •