0

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?

αғsнιη
  • 2,627
  • 2
  • 25
  • 38
afskymonkey
  • 17
  • 1
  • 4
  • Unfortunately I don't think sed supports the non-greedy operator `?`. See [here](https://stackoverflow.com/q/1103149) – Prime Oct 26 '17 at 03:46

5 Answers5

1

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
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
0

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//#+([^ ])/}"
αғsнιη
  • 2,627
  • 2
  • 25
  • 38
0

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
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
0

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
dawg
  • 98,345
  • 23
  • 131
  • 206
0

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*//'
Djory Krache
  • 347
  • 4
  • 9