Usage of tail command in .awk

Hi,

I want to do file format using awk script, for that i wan to use 'tail'. Here is the scenario. I will be having set of files in a directory. Those files i need to write to another directory with same file name, but while writing the file to out directory, i need to write the last line as first line and the rest will follow in the same order. For example, the file has below content

one
two
three
four

The file with the same name in output directory should be like

four
one
two
three

I tried like below, but wasn't working

BEGIN {
	while ( ( "ls -l "ARGV[1] | getline line ) > 0 ) 
	{
		n = split(line, fileName, " ")
		if (fileName[n] > 0)
		{
			count=0
			while ((getline < (ARGV[1] "/" fileName[n]))>0) 
			{				
				dLine = $0
				if (count == 0) 
				{
					#temp = `$(tail -1 $(ARGV[1] "/" fileName[n]))`
					sed -ne 1 $ARGV[1] "/" fileName[n] > ARGV[2] "/" fileName[n]
					printf "\n" >> ARGV[2] "/" fileName[n]
					printf dLine >> ARGV[2] "/" fileName[n]
					printf "\n" >> ARGV[2] "/" fileName[n]
				}
				
				if (count != 0 && substr(dLine ,1,1) != "H")
				{
					printf dLine >> ARGV[2] "/" fileName[n]
					printf "\n" >> ARGV[2] "/" fileName[n]
				}
				count = count+1
			};	
		}
	}
}

Venkata Madhu

A simple approach is to count the number of lines with wc, then use tail and head.

Regards,
Alister

---------- Post updated at 01:43 PM ---------- Previous update was at 01:40 PM ----------

More efficiently, dispense with wc and simply use tail and sed (using $ to avoid reprinting the final line).

Regards,
Alister

`` and $( ) are shell syntax, they do not work inside awk. If they are processed at all they will be processed once, before awk is run, by the shell.

It might be easier to use awk's built-in file processing loop than fighting it by cramming it all in BEGIN. Less duplicated logic.

How about this:

find path/to/folder -type f | xargs awk '
# Call this function whenever the filename changes
function flush(F) {
        if(L) {
                F=LF;
                sub(OLDNAME, NEWNAME, F);
                if(F == LF)
                        print "WARNING, outfile=infile" >"/dev/stderr";
                else
                {
                        print LINE[L] > LF; # Print last line first
                        for(N=1; N<L; N++) print LINE[N] > LF; # Print other lines in order
                        close(LF); # Close file to avoid too-many-files error
                }
                L=0; # Reset line number
        }

        LF=FILENAME; # Store filename
}

LF != FILENAME { flush(); }
# Store every line from current file
{ LINE[++L]=$0 }
# Have to flush the very last file too
END { flush(); }' OLDNAME="/abc" NEWNAME="/def"

Use nawk on Solaris.

OP, Why are you trying to write a simple sh script in awk. A simple for-loop should do.

Regards,
Alister