-4

we have file with many "%" characters in the file

we want to add before every "%" the backslash

as

\%

example

before

%TY %Tb %Td %TH:%TM %P

after

\%TY \%Tb \%Td \%TH:\%TM \%P

how to do it with sed ?

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
yael
  • 12,598
  • 51
  • 169
  • 303
  • If it's a [cron file](https://unix.stackexchange.com/q/465556/117549), I would be cautious, in case the creator of the file ever *really* wanted to use % for sending stdin to the job. Consider [simpler wrapper scripts](https://unix.stackexchange.com/a/465575/117549) instead of gambling on precise syntax. – Jeff Schaller Aug 29 '18 at 19:13

1 Answers1

6

Pretty straightforward

$ echo '%TY %Tb %Td %TH:%TM %P' | sed 's/%/\\%/g'
\%TY \%Tb \%Td \%TH:\%TM \%P

but you can accomplish the same with bash parameter substitution

$ str='%TY %Tb %Td %TH:%TM %P'; backslashed=${str//%/\\%}; echo "$backslashed"
\%TY \%Tb \%Td \%TH:\%TM \%P
glenn jackman
  • 84,176
  • 15
  • 116
  • 168