0

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?

1 Answer 1

1

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
7
  • Can I just paste this to terminal or how do I run this?
    – Lauri
    May 29, 2015 at 4:26
  • Never mind, I managed to run it. Would it be hard to modify this script so that instead of renaming the link.txt it would rename the parent folder? So in my previous example case the folder named "1".
    – Lauri
    May 29, 2015 at 5:13
  • Do you mean to rename 1/link.txt to become (for example) name/link.txt? May 29, 2015 at 6:12
  • Yes exactly like that.
    – Lauri
    May 29, 2015 at 6:19
  • See my edited answer. BTW it is not tested May 29, 2015 at 6:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .