Results 1 to 4 of 4
  1. #1
    Join Date
    Sep 2003
    Posts
    12

    Unanswered: Renaming files based on contents

    Hi All,

    I've got a directory full of csv files: 1.csv, 2.csv, 3.csv and so on. What I'm trying to do is read each csv file and rename that file based on the output of line 2 in that file. For instance: cat 1.csv | awk 'NR==2' would return blue, I want to rename 1.csv to blue.csv. I've tried a few different things including:

    ls *.csv > list

    for i in `cat list`;do cat $i |awk 'NR==2 {print "mv "$i" "$1".csv"};done > executeme

    The file executeme would then be ran and change the name of each of the files. However, the execute file doesn't have what exactly what I want (mv blue blue.csv). And, I believe a better / faster way of going about this is out there. Or, I just need to make some adjustments. Anyhow, any help or suggestions would be greatly appreciated.

    TIA!!

  2. #2
    Join Date
    Sep 2009
    Location
    Ontario
    Posts
    1,057
    Provided Answers: 1
    for file in `ls *.csv`
    do
    mv $file `cat $file |awk 'NR==2'`.csv
    done

  3. #3
    Join Date
    Sep 2003
    Posts
    12
    Wow, that was easy enough. I guess I was headed in the right direction, I just took the wrong turn. Thank you very much!!

  4. #4
    Join Date
    Oct 2002
    Location
    Baghdad, Iraq
    Posts
    697
    Quote Originally Posted by kitaman View Post
    for file in `ls *.csv`
    do
    mv $file `cat $file |awk 'NR==2'`.csv
    done
    Better: for file in *.csv; do mv "$file" `cat "$file" | awk 'NR==2'`.csv; done

    This won't choke on, e.g. spaces in filenames.

Posting Permissions

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