Hello and thanks in advance.

I need to take a file, insert the filename as the first line of the file, then move to a different name. Here's the wrinkle. I need to grab the oldest file in the format of ORIGFILE_YYYYMMDD.TXT and save it as NEWFILE.TXT. For this example, let's say the file name is ORIGFILE_20151117.TXT

  1. Grab oldest file (ls -tr ORIGFILE*.txt)
  2. Add ORIGFILE_20151117.TXT as first line of file
  3. Rename/Move ORIGFILE_20151117.TXT to NEWFILE.TXT
  • Write the filename to newfile.txt and then append the entire contents of origfile_20151117.txt. After that delete the original file. – roaima Nov 17 '15 at 21:58

Well, let's break this down into simple steps:


# First, let's get that file's name:
FILE=$(ls -rt ORIGFILE*.txt | tail -n1)
if [[ 0 -ne $? ]]; then
    echo "Unable to locate matching file.  Aborting." 1>&2
    exit 1

# Now, create a new file containing the file's name:

# And append the contents of the old file into the new:

# Finally, get rid of the old file: (uncomment if you're sure)
# rm "$FILE"

This will do the trick:

f=$(ls -1tr ORIGFILE*.txt | head -1); echo $f | cat - $f > NEWFILE.txt && rm $f
  • Only if the filenames don't contain nonprintable characters. – Kusalananda Oct 16 '18 at 9:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.