Output matching pattern whilst retaining the line they existed on - bash

awk to the rescue!

$ awk '{for(i=1;i<=NF;i++) if($i~/d$/) printf "%s ",$i; print ""}' file

0.44d 0.55d 0.33d
6.442d 1.515d 1.23d
2.46d 9.35d 0.83d
4.46d
5.34d 5.55d
6.02d
2.7d
0.004d
0.96d 1.113d
423.99d 0.1d 0.9d 0.117d

Here is a solution with sed:

sed -E 's/[^[:space:]]*[^d]([[:space:]]|$)//g'

I just inverted your initial logic: instead of displaying fields that end with d, I remove fields that don't.


Perl oneliner:

perl -lane 'print join " ", grep {/d$/} @F' test.txt

The -e flag gives the next argument as the code to execute.
The -n flag tells perl to wrap the given code in a loop, iterating over the files of the given file(s)/stdin, without automatically printing the line.
The -a flag splits the line into fields stored in the @F array.
The -l flag handles automatically removing and re-adding the EOL newline.

Tags:

Grep

Awk

Sed