Question

I'm fairly new to using bash.

I have several hundred documents, each named QP1172, QP1474, QP9926, etc. I need the name of the file to be in the first row of the document (so QP1172 for example would be in row 1 of the document QP1172.txt).

Does anyone know how I could do this? Thank you!

Was it helpful?

Solution

You could do something like

for f in QP????.txt; do echo $f | cat - $f >$f.withname; done

to create new files QP1172.txt.withname etc., and then replace the old ones with them after checking that everything looks ok.

(cat here concatenates the name (given on standard input) with the file contents of each file.)

ADDED: To make it easier to let the new versions get the right name afterwards it might be easier to let them have the same name, but in another directory.

mkdir withname
for f in QP????.txt; do echo $f | cat - $f >withname/$f; done

OTHER TIPS

You could use sed to insert a line at the beginning:

for f in QP*; do
    sed -i "1i$f" "$f"
done

1i$f means "insert a line containing the value of $f before line 1".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top