1

First off, I'm really bad at shell, as you'll notice :)

Now then, I have the following task: The script gets two arguments (fileName, N). If the number of lines in the file is greater then N, then I need to cut the last N lines, then overwrite the contents of the file with it.

I thought of saving the contents of the file into a variable, then just cat-ing that to the file. However for some reason it's not working.

I have problems with saving the last N lines to a variable.

This is how I tried doing it:

lastNLines=`tail -$2 $1`
cat $lastNLines > $1
6
  • Maybe I misunderstood, but wouldn't tail -n N inFile > outFile be good enough? Commented Nov 16, 2013 at 20:47
  • @pfnuesel the problem is the OP wants to overwrite the same file he's reading from. Commented Nov 16, 2013 at 20:49
  • tail -n N inFile > outFile && mv outFile inFile Commented Nov 16, 2013 at 20:49
  • @pfnuesel By the looks of it, he's trying to write to the same file he's reading from. When you end something in >$1, Bash will open it for writing, thus emptying the file, before executing tail. In other words, tail would just find an empty file. Commented Nov 16, 2013 at 20:50
  • I still don't see why my suggestion wouldn't work. Commented Nov 16, 2013 at 21:02

2 Answers 2

2

Your lastNLines is not a filename. cat takes filenames. You also cannot open the input file for writing, because the shell truncates it before tail can get to it, which is why you need to use a temporary file.

However, if you insist on not using a temporary file, here's a non-portable solution:

tail -n$2 $1 | sponge $1

You may need to install moreutils for sponge.

Sign up to request clarification or add additional context in comments.

Comments

1

The arguments cat takes are file names, not the content.

Instead, you can use a temp file, like this:

tail -$2 $1 > $1._tmp
mv $1._tmp $1

To save the content to a variable, you can do what you already included in your question, or:

lastNLines=`cat $1`

(after the mv command, of course)

1 Comment

Okay, and how about saving the contents of the file to a variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.