Search code examples
bashcut

Process lines of text with bash


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 :-)


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