Wednesday, July 27, 2022

[SOLVED] Linux - Get Substring from 1st occurence of character

Issue

FILE1.TXT

0020220101

or

01 20220101

Need to extra date part from file where text starts from 2

Options tried:

t_FILE_DT1='awk -F"2" '{PRINT $NF}' FILE1.TXT'
t_FILE_DT2='cut -d'2' -f2- FILE1.TXT'

echo "$t_FILE_DT1"
echo "$t_FILE_DT2"

1st output : 0101

2nd output : 0220101

Expected Output: 20220101

Im new to linux scripting. Could some one help guide where Im going wrong?


Solution

Use grep like so:

echo "0020220101\n01 20220101" | grep -P -o '\d{8}\b'
20220101
20220101

Here, GNU grep uses the following options:
-P : Use Perl regexes.
-o : Print the matches only (1 match per line), not the entire lines.

SEE ALSO:
grep manual
perlre - Perl regular expressions



Answered By - Timur Shtatland
Answer Checked By - Dawn Plyler (WPSolving Volunteer)