renaming according to text search

hello

does someone want to help me for this one ?

i want to rename text file with something written in that file
so far i've used grep in the first 20 lines of the text, to find these words (translation from) or (translated from)
i need to take the name after these words (everything until the end of line) and mv it in the filename before extension

this script is helping me

find . -type f -exec grep -il 'HELLO' {} \; -exec mv {} {}.hello \;

but now i'm stucked & i don't know how to move 'the grep finding' in the filename
here is what i've done by now

find . -type f -name "*.txt" -exec grep -wi "\(translated from\)" <(head -n 20 *.txt) {} \; -exec mv -- "$f" "${f%.txt}\ --\ translated\ from \.txt" \;

of course that doesn't work only some parts work
works

grep -wi "\(translated from\)" <(head -n 20 *.txt)

thanks for you help !

Can you post the sample data?

This will not work because "{}" can only be used ONCE in an exec clause. If you want this to work you will have to write a small script, like this (stripped down to the bare minimum):

# cat /usr/local/bin/findhelper.sh
#! /bin/sh
mv "$1" "${1}.hello"

# find . -type f -exec grep -il 'HELLO' {} \; -exec /usr/local/bin/findhelper.sh {} \;

You can probably adapt the script to do what you want to achieve.

I hope this helps.

bakunin

1 Like

here is a example of text file, as you can see before the first 20 lines there is the occurence (translated from)
and after (Denis Roche)

so for that file the filename need to become :
les moujiks -- translated by denis roche.txt

if i use

find . -type f -exec grep -wil "\(translated from\)" {} \; -exec mv {} {}.translated\ from \;

i got the right thing regardind to the command and the filename become (les moujiks.txt.translated from)

so the grep & mv commands works well

but i don't know how to move the grep findings (the words after translated from) to the filename to got in final (les moujiks -- translated by denis roche.txt)
les moujiks.txt.translated from

A bit convoluted but works:

printf "%s\n" *.txt|while read fname
do
if awk 'match($0,/translat(ion|ed) from/){
t=substr($0,RSTART)
gsub(/[^A-Za-z0-9_ -]/,"",t)
if(length(t)){print t;exit(0)}}
END{if(!length(t)) exit(1)}' <(head -20 "$fname") > temp
then
 mv "$fname" "${fname%.txt}_$(<temp).txt"
fi
done

If your grep supports the -m and -o switches, you could simplify this. But, then you'll have to make sure that you don't have some "wild" characters in the matching strings.

1 Like

thanks for your helpings to all, i really appreciate it !

this script works perfectly !