Mathias F
Mathias F

Reputation: 15911

Replace token in text by the filename

I have a bunch of textfiles that contain the token -filename-. I need to replace it by the real path and filename of the file.

Thats what I have so far:

grep -lr -e '-filename-' *.txt | xargs sed -i 's/-filename-/therealname/g'

Is there a way to replace therealname with the name of the file?

Upvotes: 4

Views: 3019

Answers (3)

Zsolt Botykai
Zsolt Botykai

Reputation: 51643

for f in YOUR_FILE_LIST_MASK ; do
    sed -i "s:-filename-:${f}" ${f}
done

can do it.

Upvotes: 0

Dave
Dave

Reputation: 11162

Just do a bit more bash-fu

for x in *.txt; do
    sed -i "s/-filename-/$x/g" $x;
done

Of course, the newlines are just for clarity. Feel free to cram that into one line.

Upvotes: 5

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143229

like

for f in $(grep...) ; do sed -i "s,-filename-,$f,g" $f ; done

you mean?

With xargs it will be something like this.

grep ... | xargs -I% -n 1 sed -i "s,-filename-,%,g" %

Upvotes: 2

Related Questions