문제

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!

도움이 되었습니까?

해결책

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

다른 팁

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".

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top