-1

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?

  • Can you list the files to get filename exemple? Thanks. – Kevin Lemaire Feb 2 '18 at 10:21
  • An example would be: BLA_BLUB_BLURR_20180123231157.csv.gz – LaaKii Feb 2 '18 at 10:22
3

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;
  • ${filename:$((-21)):-7} (in bash) would also pick out the date stamp, if the file name suffix is always the same length. – Kusalananda Feb 2 '18 at 10:37
  • 1
    It isn't always the same length. Thanks anyway! – LaaKii Feb 2 '18 at 10:38
  • 1
    @Kusalananda, ${filename: -21:-7} is enough to disambiguate it from ${par:-} (space between the : and -). And actually that's an arithmetic context anyway, so you could do even ${filename:0-3*7:-7} without the $(( )). – ilkkachu Feb 2 '18 at 10:53
  • @ilkkachu Thanks! I was scratching my head over that, but not for long enough it seems :-) – Kusalananda Feb 2 '18 at 10:57
  • 1
    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}... – Stephen Kitt Feb 2 '18 at 12:39
0

You are missing and echo inside the Command execution expansion, but better to use printf:

result=$(echo "$filename" | grep -Eo '[[:digit:]]{14}')

result=$(printf '%s' "$filename" | grep -Eo '[[:digit:]]{14}')

Of course, there is the chance that result is NULL if the file does not match the grep regex, for that we need a test:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.