0

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!!

2
  • I wouldn't recommend bash for general text processing, but it's capable of manipulating (and validating) filenames. Are you opposed to a shell/bash-based solution?
    – Jeff Schaller
    Jun 15 at 0:56
  • The code that I have has #!/bin/bash which is the reason I am using bash commands. I'm new to this so understand everything with a google search right now! Jun 15 at 1:35

0

Your Answer

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

Browse other questions tagged or ask your own question.