Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 5 down vote accepted

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"
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.