Question

I'm saving a file with dates and file names with this structure:

date1 name1
date2 name2
...
dateN nameN

Afterwards I'm reading the file with the while command and trying to compare if the date field is equal to a date given. If the date is the same, I'm saving the name and then printing it.

while read line
do
    if [ ‘$($line | cut -c 1-10)’ == ‘$(date +%Y-%m-%d)’ ]
    then
        name=$($linea | cut -c 12-100)
    fi
    echo $name
done < archivos.txt

After executing the script, the console is giving me every date into the file with the 'command not found' error.

Thanks in advance :-)

Was it helpful?

Solution

Your approach is interesting, but it may be easier to skip the use of a while loop and use awk all together, giving the date as parameter:

awk '$1~d {print $2}' d=$(date +%Y-%m-%d) archivos.txt
  • $1~d {print $2} if the first field matches the date given, print the 2nd field.
  • d=$(date +%Y-%m-%d) pass today's date to awk.

Sample

$ cat a
2014-01-28 hello
2014-01-28 byetwo
2014-02-28 bye
2014-01-29 bye

$ awk '$1~d {print $2}' d=$(date +%Y-%m-%d) a
hello
byetwo

OTHER TIPS

The way your code is written, you are trying to execute $line as a command. You need to use echo or printf to write the line to stdout instead:

$(printf %s "$line" | cut -c 1-10)

This happens because your script can't find the date command. This gives you two options.

Option 1: Locate the date binary and give the full path

Run "whereis date" in your command prompt and it should output something liket his date: /bin/date /usr/share/man/man1/date.1.gz You can then either change

$(date +%Y-%m-%d)

to

$(/bin/date +%Y-%m-%d)

Option 2: Export a path where the binary should be looked for

The reason date can't be found is because it's not in the script's PATH variable. You can either just add /bin/ to PATH or have the same as you have in your shell. Run echo $PATH in your shell and it should output something liket his

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

What you then can do then is to set the scripts PATH variable to the same thing so it would look like this:

export PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
while read line
do
    if [ ‘$($line | cut -c 1-10)’ == ‘$(date +%Y-%m-%d)’ ]
    then
        name=$($linea | cut -c 12-100)
    fi
    echo $name
done < archivos.txt
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top