Search for lines by pattern, leave only the pattern, but keep unmatched lines as they are
So there is a file with res.txt file like this
processing file 0x8001.values
channel 1: 123
channel 2: 234
channel 3: 345
processing file 0x8002.values
channel 1: 456
channel 2: 567
channel 3: 678
I have a template like this
0x[0-9a-f][0-9a-f][0-9a-f][0-9a-f]
Using for example
grep -o "0x[0-9a-f][0-9a-f][0-9a-f][0-9a-f]" res.txt
I can get a list of my filenames (no .values), which is good!
0x8001 0x8002
Still, all other lines that do not match the pattern remain where they are:
0x8001
channel 1: 123
channel 2: 234
channel 3: 345
0x8002
channel 1: 456
channel 2: 567
channel 3: 678
I'm pretty familiar with sed, but couldn't find a way to do what I want.
+3
source to share
2 answers
Using gnu awk you can use a match
function like this with your regex:
awk 'match($0, /0x[0-9a-f][0-9a-f][0-9a-f][0-9a-f]/){$0=substr($0,RSTART,RLENGTH)} 1' file
0x8001
channel 1: 123
channel 2: 234
channel 3: 345
0x8002
channel 1: 456
channel 2: 567
channel 3: 678
+1
source to share