Result of grep can't be stored in variable

5,291

You dropped the echo:

for filename in OH/*
do
    result=$(echo $filename | grep -Eo '[[:digit:]]{14}')
    echo "$result"
done;

or better yet,

for filename in OH/*
do
    result=$(printf %s "$filename" |grep -Eo '[[:digit:]]{14}')
    echo "$result"
done;

or

for filename in OH/*
do
    result=$(grep -Eo '[[:digit:]]{14}' <<<"$filename")
    echo "$result"
done;
Share:
5,291

Related videos on Youtube

LaaKii
Author by

LaaKii

Updated on September 18, 2022

Comments

  • LaaKii
    LaaKii almost 2 years

    I want to get a date from a file name. This works using this code:

    for filename in OH/*
    do
        echo $filename |grep -Eo '[[:digit:]]{14}'
    done;
    

    Now i want to save the result to a variable like this:

    for filename in OH/*
    do
        result=$($filename |grep -Eo '[[:digit:]]{14}')
        echo $result
    done;
    

    But i get 2 empty lines printed. What am i missing there?

    • Kevin Lemaire
      Kevin Lemaire over 6 years
      Can you list the files to get filename exemple? Thanks.
  • Kusalananda
    Kusalananda over 6 years
    ${filename:$((-21)):-7} (in bash) would also pick out the date stamp, if the file name suffix is always the same length.
  • LaaKii
    LaaKii over 6 years
    It isn't always the same length. Thanks anyway!
  • Kusalananda
    Kusalananda over 6 years
    @ilkkachu Thanks! I was scratching my head over that, but not for long enough it seems :-)
  • rien333
    rien333 over 6 years
    Why not grep -Eo $filename '[[:digit:]]{14}'? Seems more portable than using <<< .
  • Stephen Kitt
    Stephen Kitt over 6 years
    rien333, that would look for the pattern $filename (or rather, the pattern corresponding to the value of the filename shell variable) in a file named [[:digit:]]{14}...
  • done
    done over 6 years
    There is a clear chance that some other files will match the glob OH/* but not the grep regex. In such case, a NULL result will be printed. Avoid with `[ "$result" ] && echo "$result"
  • done
    done over 6 years
    Quoting "$result" seems reasonable. Edit done.
  • done
    done over 6 years
    No, it is not related to the empty (NULL) comment. That is why it is a separate comment. It is related to "quoting your expansions" as a reasonable good coding practice. I assumed you know it, that's why I directly did the edit. Better now? :-)
  • Stephen Kitt
    Stephen Kitt over 6 years
    @isaac right that makes sense, thanks for the edit. “Quoting "$result" seems reasonable” is the sort of thing I would write in the edit comment, not as a post comment ;-).