Change the field separator
4
1
Entering edit mode
3.8 years ago
ATCG ▴ 380

Hi, I have the following character:

CG10226/CG33120/RyR/Tsp42Eg/CG1234/Act57B/Apoltp/CG9194

and need to change the field separator from "/ " to "," so that my character will look like this:

CG10226,CG33120,RyR,Tsp42Eg,CG1234,Act57B,Apoltp,CG9194

Thanks in advance for your help!

R awk field separator • 1.1k views
ADD COMMENT
2
Entering edit mode
3.8 years ago
Quentin M ▴ 60

In R :

library("stringr")   
str_replace_all(string = "CG10226/CG33120/RyR/Tsp42Eg/CG1234/Act57B/Apoltp/CG9194", pattern = "/", replacement = ",")
ADD COMMENT
1
Entering edit mode

Without any additional package:

gsub("/",",","CG10226/CG33120/RyR/Tsp42Eg/CG1234/Act57B/Apoltp/CG9194")
ADD REPLY
1
Entering edit mode
3.8 years ago

depends of the context :

use awk+gsub https://www.gnu.org/software/gawk/manual/html_node/String-Functions.html if it's a token among multiple columns.

just use tr if it's the whole line.

ADD COMMENT
1
Entering edit mode
3.8 years ago
Jeffin Rockey ★ 1.3k
sed 's|\/|,|g'
ADD COMMENT
0
Entering edit mode

Hi Jeffin, Thanks for your answer. Can you be more specific please?

ADD REPLY
1
Entering edit mode

sed is a very handy utility which would be there is many of the unix/linux flavours.

s stands for substitute.

The | (pipes) act as separators. And it need not be | always. You may as well write like sed 's/\//,/g' (I am pretty sure it would confuse more, and hence the pipes)

\/ kind of says to look for / and just treat it as a character and do not mean any further meanings to it.

, is the replacement.

g indicates globally

In short, all this boils down to

sed, substitute a slash with a comma for all occurrences in the file.

You may use it like

sed 's|\/|,|g' file.txt >file.comma.sep.txt
or
sed <file.txt  's|\/|,|g'  >file.comma.sep.txt
or
echo "the/slash/separated/string" | sed 's|\/|,|g'

The above will write the output after replacement to the new file, keeping input file intact.

If you prefer to substitute inside the input file itself rather than streaming out, use -i (be very very careful with this)

ADD REPLY
0
Entering edit mode

Maybe read the manual for sed? https://en.wikipedia.org/wiki/Sed

ADD REPLY
0
Entering edit mode
3.8 years ago
zx8754 11k

Using R, just read the file with sep:

read.table("myFile.txt", sep = "/")
#       V1      V2  V3      V4     V5     V6     V7     V8
#1 CG10226 CG33120 RyR Tsp42Eg CG1234 Act57B Apoltp CG9194
ADD COMMENT

Login before adding your answer.

Traffic: 1468 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6