sed -n 's/.*STRING:[[:blank:]]*\(..*\)/\1/p' filetest.txt
You wouldn't do it in a shell loop as these are generally not ideal for parsing text (see "Why is using a shell loop to process text considered bad practice?").
Instead, the above single command uses sed
to match the regular expression (here rewritten as a basic regular expression rather as a PCRE, a Perl compatible regular expression). The editing command used with sed
replaces the matching line with the captured text and outputs it.
Another way:
awk -F ':[[:blank:]]*' '/STRING/ { print $2 }' filetest.txt
This treats each line of the file as a record with fields delimited by :
followed by any number of spaces or tabs. When the STRING
pattern is found on a line, the second such field is printed.
Would you nonetheless want to do it with a bash
loop:
while IFS= read -r line; do
if [[ $line =~ 'STRING:'[[:blank:]]*(.+) ]]; then
printf '%s\n' "${BASH_REMATCH[1]}"
fi
done <filetest.txt
The BASH_REMATCH
array will contain the various captured bits from the match. The regular expression itself (which should be an extended regular expression) should not be quoted, apart form the bits that needs to be interpreted literally. Note: This is where you went wrong; you quoted the regular expression and did not look in BASH_REMATCH
for the captured data. You also tried to use the regular expression exactly the way you would write the expression in Python. bash
is not Python.
Or,
while IFS= read -r line; do
match=$(expr "$line" : '.*STRING:[[:blank:]]*\(..*\)')
if [ -n "$match" ]; then
printf '%s\n' "$match"
fi
done <filetest.txt
Given the input that you have in the question, the various variations above will all output
"785c7208dcf0"
See also:
grep
command. (2) If you provide some representative sample input and corresponding desired output, you will get better answers. – John1024 Apr 04 '19 at 18:54filetest.txt
. – John1024 Apr 04 '19 at 19:00filetest
is the string to be analysed andouput
is the resulted – Shinomoto Asakura Apr 04 '19 at 19:45"785c7208dcf0
as the output), but the desired output does not. Which is required? – Chris Davies Apr 04 '19 at 21:09