简体   繁体   中英

Script to open latest text file from a directory

I need a shell script to open latest text file from a given directory. it will be then copied to another directory. How can i achieve it?

I need a logic which will search and give the latest file from a directory (name of the text file can be anything (not fixed), so i need to find out latest text file)

Here you can do something like this

#!/bin/sh

SOURCE_DIR=/home/juned/Downloads
DEST_DIR=/tmp/

LAST_MODIFIED_FILE=`ls -t ${SOURCE_DIR}| head -1`
echo $LAST_MODIFIED_FILE

#Open file
vim $SOURCE_DIR/$LAST_MODIFIED_FILE

#Copy file
cp $SOURCE_DIR/$LAST_MODIFIED_FILE $DEST_DIR
echo "File copied successfully"

You can specify any application name in which you want to open that file like gedit, kate etc. Here I've used vim .

xdg-open - opens a file or URL in the user's preferred application

Not an expert in bash but you can try this logic:

First, grab the latest file using ls -t -t sorts by time head -1 gets the first file

F=`ls -t * | head -1`

Then open the file using and editor:

xdg-open $F
gedit $F
...

As suggested by @ AJefferiss you can directly do :

xdg-open $(ls -t * | head -1)
gedit $(ls -t * | head -1)

In one line (if are you sure that there are only files):

vim `ls -t .|head -1`

it will be opened in vim (or use other txt editor)

if there are directories you should write script with loop and test every file (if it's not a dir):

if [ -f $FILE ];

or you can also use find, or use pipe for get latest file:

ls -lt .|sed -n 2p|grep -v '^d'

For editing the latest modified / created,

vim $(ls -t | head -1)

For editing the latest in alphanumerical order,

vim $(ls -1 | tail -1)

The existing answers are helpful, but fall short when it comes to dealing with filenames with embedded spaces or other shell metacharacters . [1]

# Get the most recently modified *.txt file.
# (On *assignment*, names with spaces, ... are not a concern.)
f=$(ls -t *.txt | head -n 1) 

# *Use* the variable enclosed in *double-quotes* to ensure that it is passed
# to the target command unmodified.
xdg-open "$f"      # could also use "$(ls -t *.txt | head -n 1)" directly

Additionally, some answer user all-uppercase shell variable names, which should be avoided so as to avoid conflicts with environment variables.


[1] Due to use of ls , filenames with embedded newlines won't be handled correctly, but that's rarely a real-world concern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM