Bash: replace with alternating symbol

172 views Asked by At

I want to extract markdown from some sort of text (ulysses iii iCloud Text.txt file). The editor replaced all square brackets with the "OBJECT REPLACEMENT CHARACTER" 0xEF 0xBF 0xBC (efbfbc) and I want to undo this operation.

How can I substitute all odd occurrences with "[" and all others by "]".

EDIT:

As example I want to replace each occurrence of x to [or ]:

Some xlinkx -> Some [link]

1

There are 1 answers

0
David C. Rankin On BEST ANSWER

You can use sed for your purpose. With sed -i it will edit the file in place making the changes needed. To create a backup of the original in file.bak use sed -i.bak. The expression would require that you place the character you want to replace in the variable char (e.g. char=x in your example). Then the following would replace all occurrence of x..stuff..x with [..stuff..]:

sed -i "s/\(^.*\)\b$char\([^$char]*\)$char\b\(.*$\)/\1[\2]\3/g" filename

Example:

$ char=x; echo "Some xlinkx" | sed -e "s/\(^.*\)\b$char\([^$char]*\)$char\b\(.*$\)/\1[\2]\3/g"
Some [link]

The expression utilizes word boundaries \b to control the match at the beginning and end of the experssion to insure first occurrence is replaced with [ and the second with ].