Issue
Let's suppose a file with following content named file.txt is used as a source.
12345
ABC-12
XCD-13
BCD-12345
Some text on this line
*+-%&
What I am looking for with sed would be to get only ABC-12 line and remove hyphen so the desired output would be ABC12
So far I have been able to get numbers only with following command:
sed "s/[^0-9]//g" file.txt
Output
12345
12
13
12345
I got the closest with grep with command:
grep -oP 'ABC-\b\d{2}\b' file.txt
Output
ABC-12
How should this be constructed with sed and also hyphen removed from the output?
Note also that numbers after ABC can be considered as changing like a variable so the idea would be to search for "ABC and numbers following it after hyphen" instead of searching for "ABC-12" directly.
Solution
idea would be to search for
ABC
and numbers following it after hyphen
You may use this sed
for this:
sed '/^ABC-[0-9][0-9]$/!d; s/-//' file
ABC12
Here:
/^ABC-[0-9][0-9]$/!d
: Searches input for a line that starts withABC
followed by a hyphen followed by 2 digits and end. All non-matching lines are removed due to!d
as command.s/-//p
: Removes-
from the match
Update:
As per comment below if ABC-
text is not at the start then use:
sed -nE 's/.*(ABC)-([0-9][0-9]).*/\1\2/p' file
Answered By - anubhava Answer Checked By - Candace Johnson (WPSolving Volunteer)