In the SED command, I only want the SED to work if there are SOMETHING_4DigitsHereOnly_SOMETHING2
.
For example, if the file name is ITALY_2022_BEST1FRIENDS2_ROME.txt
. I only want 2022_BEST1FRIENDS2
but also if it is named ITALY_202345_BEST1FRIENDS2_ROME.txt
then it should give an error because it is not 4 digits it is more than 4.
if that pattern is not found I want to give an error in the shell script.
username=$(find . -iname '*.txt' | sed -e 's/.*_\([0-9]\{4\}_[0-9|A-z]*\).*/\1/i' | sort - | uniq -ui |tr -d '\n')
grep code that does the same but gives an error if file doesn't match thanks to user @frabjous:
read filename
set -o pipefail
filename_trimmed=$(echo $filename | grep -o '[0-9]\{4\}_[0-9|A-z]*' -i | sort - | uniq -ui |tr -d '\n')
# get the exit status of the previous command
pipeexit="$?"
set +o pipefail
if [[ "$pipeexit" != 0 ]] ; then
echo "FILENAME not found" >&2
# line below quits the script; remove if you don't want that
exit "$pipeexit"
fi
echo trimmed mmc is $filename_trimmed
The previous question and more info here: Extracting a partial part from filename using SED SED and REGEX extraction and rejecting if pattern not found Thank you!!