4

How can ^ be replaced with space in Unix?

Input:

ab^cd^ef

Output:

ab cd ef

I have tried sub(/^/, " & ", str) but output is same as input.

  • 3
    In bash: echo "${str//^/ }"... – jasonwryan Aug 29 '16 at 3:41
  • 3
    Your problem is that ^ is a special character for regexps. – Stig Hemmer Aug 29 '16 at 10:52
  • 4
    You say sub(/^/, " & ", str) but what language is that? (It looks vaguely Perl-ish to me, but without context, it's really hard to tell.) Best is if you can provide a ready-made script (including a #!) that people can directly execute which demonstrates exactly the problem you are having and nothing more. – a CVn Aug 29 '16 at 12:21
  • 2
    @MichaelKjörling, that's awk. – Stéphane Chazelas Aug 29 '16 at 14:08
16

That's the job for tr:

$ str=ab^cd^ef
$ printf '%s\n' "$str" | tr '^' ' '
ab cd ef

In bash, ksh93, mksh, zsh:

printf '%s\n' "${str//^/ }"

In zsh:

print -rl -- "${str:gs/^/ /}"
7

Using sed,

$ echo "ab^cd^ef" | sed 's,\^, ,g'
ab cd ef

Already commented by @jasonwryan you can use inline shell string replacement,

$ str="ab^cd^ef"
$ echo "${str//^/ }"
ab cd ef

Another one, suggested by @someonewithpc

$ echo "ab^cd^ef" | sed 'y,^, ,'
ab cd ef

(Note : y is used for transforming characters.)

  • 1
    I'd prefer to use 'y/^/ /' – someonewithpc Aug 29 '16 at 19:41
  • @someonewithpc thanks, incorporated your suggestion in my answer. If you would like, post it as a separate answer. – Rahul Aug 31 '16 at 6:07
2

Assuming you want to do the substitution in awk as your

sub(/^/, " & ", str)

suggests, you'd need to escape the ^ as that's an extended regular expression operator (/^/ means match at the beginning of the string):

sub(/\^/, " & ", str)

would replace the first occurrence of ^ within str with ^ (space-^-space). Use sub(/\^/, " ", str) to replace with space, and gsub(/\^/, " ", str) to replace every occurrence.

Note that you can't use sub(/[^]/, " & ", str) as ^ happens to also be special inside [...]. Most awk implementations support sub(/[\^]/, " & ", str) though.

  • How about set FS to ^ and OFS to space – cuonglm Aug 29 '16 at 14:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.