0

I started working on a script to rename files based on timestamp. I thought I had it worked out on the command line but not working as a script. Script hangs in the awk line.

This is the little script so far.

#!/bin/bash
#renamePhotos.sh
#  a script to rename photos in current directory based on date
#  to be expanded

#  OUTPUT in $(ls -tr *.JPG); 
LIST="$(ls --full-time -tr *.JPG)"
echo "Starting..."

for i in "$LIST"; do
    echo  $(awk '{ print $6 }' | awk 'BEGIN { FS = "-" }; { print $1 }')
    echo
done
RGB
  • 5
  • 2
    AWK is not hanging, it is waiting for input. I do not see i being used the awk line! Instead of awk you can use cut -f 6 to get the 6th field. – SACHIN GARG Aug 24 '16 at 04:31
  • can you please post sample input and output data ? – Rahul Aug 24 '16 at 05:45
  • Please don't parse the output of ls — if you want to do this in a shell script, use stat with a format string to directly get the information you want in the appropriate format. – Stephen Kitt Aug 24 '16 at 08:19
  • thanks for the help I managed to get a result using this line echo "$i" | awk '{ print $6 }' | awk 'BEGIN { FS = "-" }; { print $1 $2 $3 }' but now I realized my loop is not getting me what I want as @ilkkachu alludes to below. – RGB Aug 24 '16 at 15:45

1 Answers1

1

In this line:

echo  $(awk '{ print $6 }' | awk 'BEGIN { FS = "-" }; { print $1 }')

The first awk inside the command substitution doesn't have any input specified, so it reads from stdin, which is connected to your terminal, meaning that it waits for you to give it some input.

To give it some input from shell variable, you'd likely want to pipe it in:

echo "$var" | awk...

Doing echo $(foo bar) looks odd, since echo will just print the output of the command foo bar which would happen in any case if you just ran foo bar by itself. (Apart from word-splitting, but it's likely that wasn't what you were looking for.)

Also, the for loop.

for i in "$LIST"; do

will only run once, with i set to the value of LIST. Since $LIST is quoted, it doesn't go through word-splitting, and for only sees one item in the list. Though if you do it without quotes, as in for i in $LIST; do..., you'll see that it splits on spaces too. You'd need to set IFS to a newline to stop that.

Even after that there's the possible problem that the output of ls can be a bit tricky: the time format might change according to the locale (though I'm not sure if that happens with --full-time), and it can mangle unprintable characters in file names. If you know your locale and that the file names are "nice", it might work.

An alternative would be to let the shell find the files, and use something like date --reference $file (if you have that), to get the date:

for f in *.jpg ; do 
    d=$(date +"%Y-%m-%d" -r "$f")  
    echo "$d $f" 
done

(GNU coreutils date has the --reference flag. date -r on OS X takes a time instead of a file.)

ilkkachu
  • 138,973