Lord Zsolt
Lord Zsolt

Reputation: 6557

Shell - saving contents of file to variable then outputting the variable

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

Upvotes: 1

Views: 43

Answers (2)

RoliSoft
RoliSoft

Reputation: 755

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.

Upvotes: 2

shx2
shx2

Reputation: 64298

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)

Upvotes: 1

Related Questions