If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Data Access, Manipulation & Batch Languages > Unix Shell Scripts > Renaming files based on contents

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 05-12-10, 12:30
kasparaitis kasparaitis is offline
Registered User
 
Join Date: Sep 2003
Posts: 12
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!!
Reply With Quote
  #2 (permalink)  
Old 05-12-10, 17:19
kitaman kitaman is offline
Papabi's friend
 
Join Date: Sep 2009
Location: Ontario
Posts: 629
for file in `ls *.csv`
do
mv $file `cat $file |awk 'NR==2'`.csv
done
Reply With Quote
  #3 (permalink)  
Old 05-12-10, 17:57
kasparaitis kasparaitis is offline
Registered User
 
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!!
Reply With Quote
  #4 (permalink)  
Old 05-16-10, 19:21
sco08y sco08y is offline
Registered User
 
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.
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On