afskymonkey
afskymonkey

Reputation: 17

Bash output remove text between two characters

I have the output of a bash command:

8.8.8.8#53 google-public-dns-a.google.com. A

I would like to add to the bash command a regex expression to remove from the # to the next space, for the desired output of:

8.8.8.8 google-public-dns-a.google.com. A

I have tried piping the output to sed 's/#.*?\s//' (which in theory would also remove the trailing space, but this is acceptable), but output remains the same as the original.

Any suggestion on how to achieve the desired output?

Upvotes: 0

Views: 282

Answers (5)

Djory Krache
Djory Krache

Reputation: 347

sed don't support the "non greedy" operator.

But I think you can dot this easily. doing

echo "8.8.8.8#53 google-public-dns-a.google.com. A" |sed 's/#\w*//'

Upvotes: 0

dawg
dawg

Reputation: 103714

Bash itself has sed quality regex capability built in (if a bit more wordy...)

You can do:

$ txt="8.8.8.8#53 google-public-dns-a.google.com. A"
$ [[ $txt =~ ^([^#]+)#[^[:space:]]+(.*) ]] && echo ${BASH_REMATCH[1]}${BASH_REMATCH[2]}
8.8.8.8 google-public-dns-a.google.com. A

Upvotes: 0

αғsнιη
αғsнιη

Reputation: 2761

Use sed as following.

sed 's/#[^ ]*//'

Remove # followed by everything which is non-space until first space seen.

Or in bash with same:

str='8.8.8.8#53 google-public-dns-a.google.com. A'
echo "${str//#+([^ ])/}"

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133428

You could try following sed too once.

sed 's/\([^#]*\)\([^a-zA-Z]*\)\(.*\)/\1 \3/g'   Input_file

Output will be as follows.

8.8.8.8 google-public-dns-a.google.com. A

Upvotes: 0

Charles Duffy
Charles Duffy

Reputation: 295278

You don't need sed, awk, or any other tooling that isn't the shell's own built-in string operations.

shopt -s extglob

s='8.8.8.8#53 google-public-dns-a.google.com. A'
s_pruned="${s//#+([[:digit:]])/}"
echo "$s_pruned"

...properly emits:

8.8.8.8 google-public-dns-a.google.com. A

Upvotes: 1

Related Questions