In place line numbering

{ rm -f file10 && nl > file10; } < file10
Add permanent line numbers to a file without creating a temp file. The rm command deletes file10 while the nl command works on the open file descriptor of file10 which it outputs into a new file again named file10. The new file10 will now be numbered in the same directory with the same file name and content as before, but it will in fact be a new file, using (ls -i) to show its inode number will prove this.

By: zlemini
2010-04-08 21:08:23
nl rm

What Others Think

It should be noted that this can be dangerous. If the command fails for some reason (disk full, syntax error, Ctrl-C pressed, whatever), you'll have an empty file and no backup. I think it's always better to use a temporary file: nl file10 > && mv -f file10
inof · 633 weeks and 1 day ago
Your comments about syntax, disk full etc are not specific to this command, they apply to most of the commands on this site. Be advised, the 'rm' command above deletes the directory entry which is only a reference to the actual inode. Be more specific as to why you think it is dangerous and i will glady look into improving it.
zlemini · 633 weeks and 1 day ago
I agree with inof. Both versions use two inodes and just manipulate dentries to get the naming right, so neither is more efficient. But inof's version obviously can be interrupted, and the mv doesn't happen until nl has finished. Whereas with rm && nl you may interrupt, and have rm complete without nl finishing, and you are left without a file. It is true that a similar criticism applies to many of the commands at this site, but in this case by rearranging the operations, I think the "danger" is lessened. I think relying on the dentry/inode behavior of the filesystem layer is neat, but inof's version is more OS-agnostic. Would this work under Cygwin?
bwoodacre · 633 weeks and 1 day ago
The issues with replacement using this method are documented at:
pixelbeat · 632 weeks and 5 days ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this? is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands

Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.


Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: