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;
Related videos on Youtube
Author by
LaaKii
Updated on September 18, 2022Comments
-
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 over 6 yearsCan you list the files to get filename exemple? Thanks.
-
-
Kusalananda over 6 years
${filename:$((-21)):-7}
(inbash
) would also pick out the date stamp, if the file name suffix is always the same length. -
LaaKii over 6 yearsIt isn't always the same length. Thanks anyway!
-
Kusalananda over 6 years@ilkkachu Thanks! I was scratching my head over that, but not for long enough it seems :-)
-
rien333 over 6 yearsWhy not
grep -Eo $filename '[[:digit:]]{14}'
? Seems more portable than using<<<
. -
Stephen Kitt over 6 years
rien333
, that would look for the pattern$filename
(or rather, the pattern corresponding to the value of thefilename
shell variable) in a file named[[:digit:]]{14}
... -
done over 6 yearsThere 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 over 6 yearsQuoting
"$result"
seems reasonable. Edit done. -
done over 6 yearsNo, 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 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 ;-).