Rename beginning of file name using specific text in the file itself

renamesedtext processing

I have many files in directory (file1.txt, file2.txt, …)

Every files contains bunch of lines. One of the line is specific text thetext followed by random number just like thetext56, thetext21, etc.

I want to rename beginning of the file name using specific text in the file itself. So, file1.txt will be thetextXXfile1.txt, file2.txt will be thetextXXfile2.txt, and so on.

Simple rename command to add addtext on the beginning is

rename 's?^?addtext?' *.html

while getting that specific text in the files is

sed '/thetext/!d' *.html

but I have no idea how to combine both of them.

Best Answer

I would suggest that grep is a better tool for sed when what you want to do is read one line out of a file based on a match. You are welcome to substitute your sed in the loop structure below. Note that I also used the -m 1 option so that grep only bothers looking as far as the first match:

for file in *.html; do
   text="$(grep -m 1 "thetext" "$file")"
   rename "s?$text?" "$file"
done
Related Question