putting a line in a filename (with sed)

"How can I cut a line from a file and paste the rest into a file whose title is the line I just cut?"

If you find yourself asking yourself this question with any degree of regularity, you may have issues. Luckily for you, the help you so desperately need is at hand. It is not the help you want, but it is the help you deserve. For added complication let's assume you want to do this for every line in the file.

Solution (bash):

    > for i in $(seq `wc -l < FILENAME`)
    > do
    >   sed ''$i'd' FILENAME > something_else_maybe-`sed -n ''$i'p' FILENAME`
    > done

What is going on here is the following:

  • seq N prints a sequence of integers, 1 to N.
  • wc -l < FILENAME produces the number of lines in FILENAME. The normal way I do this is wc -l FILENAME, but that also prints the name of the file, which would confuse seq.
  • Enclosing a bash command in ` ` (note these are not ' or ", these are backticks (also known as grave accents (bracket nesting))) replaces the command string with the output of the command. $() also does this. Why are there two ways to do this, and why did I use both of them in my solution? We may never know.
  • sed 'Md' FILENAME, as per the rules of sed, has FILENAME as output, having deleted line M (in our case, '$i').
  • sed -n 'Qp' FILENAME runs through FILENAME, printing nothing (the -n) flag unless otherwise instructed (with p), as occurs for line Q.
  • The "something_else_maybe" just demonstrates that you could include other elements in the output filename. Further complication could be introduced here (say replacing it with $i or whatever you want), but that is too far. Too damn far.