Replacing multiple bars (special char) with a tab using sed

I have a line like this

BRADI5G20430|BRADI5G20430.1||1

      

How do I replace a panel (single and multiple) with a tab ("\ t")? I tried this but not working

sed 's/\|+/\t/g'

      

I also want to include this line in a bash script.

+2


source to share


4 answers


you need to avoid +

$ sed 's/|\+/\t/g' file
BRADI5G20430    BRADI5G20430.1  1

      

or you can use the -r

sed option , but this time it +

will be "one or more" and you need to escape the "|" as in regex it means alternation.

$ sed -r 's/\|+/\t/g' file
BRADI5G20430    BRADI5G20430.1  1

      

or use awk, set the field separator to "|" and then set the output field separator OFS

to the tab\t



eg,

$ awk -F"|" '{$1=$1}1' OFS="\t" file
BRADI5G20430    BRADI5G20430.1          1

      

this replaces every tab "|". If you want to replace all "|" with one tab

$ awk '{gsub(/\|+/,"\t")}1' file
BRADI5G20430    BRADI5G20430.1  1

      

+3


source


I believe that the command you are looking for is actually

sed -e 's/[|]\{1,\}/\t/g'

      



Sed does not use syntax +

for one or more, but allows you to specify the number of open-ended repetitions. See here for details .

+2


source


Not sure in my head why it +

doesn't work, but it would be:

$ echo  "BRADI5G20430|BRADI5G20430.1||1" | sed -e 's/\|\{1,\}/\t/g'
BRADI5G20430\tBRADI5G20430.1\t1

      

+1


source


How did it not work?

Hint: if you see how it didn't work, you can see what you need to do to make it work - try removing parts and see how the behavior changes.

Hint # 2: the part +

that sed doesn't recognize.

sed 's/\|\|*/\t/g'

+1


source







All Articles