Sunday, December 11, 2016

macos - Rename txt files based on the file's content (OSX)



I have about 250 txt files that are all named link.txt and they have this information always on the line/row 3:




title: Some kind of title





I need some kind of script that can go through these files, grab the title and put it as the filename. The folder structure is: 1-links/20150528/1/ so would be great if I could just run the script in "1-links" and it would start looking for files named "link.txt".



I'm using Mac OSX.



Can anyone help me out?


Answer



Something like can do the work:



for i in `find . -name link.txt -type f`;
do

nn=$(sed -n -e 3p -e "s/title:\ // "$i")
mv "$i" "`dirname $i`/$nn"
done


If you want to rename last directory in the path instead of file you can use something like:



for i in `find . -name link.txt -type f`;
do
nn=$(sed -n -e 's/title: //' -e 3p $i)

odir=`dirname $i`
ndir=$(echo $odir|awk -v nn="$nn" -F\/ 'BEGIN {OFS="/"} {$NF=nn;print}')
mv "$odir" "$ndir"
done

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...