简体   繁体   中英

How to replace spaces with points at even positions in a line using linux command

I have a file where I am trying to replace the spacing at even positions with two points. What linux command Can I use to do it?

I tried the following sed command sed 's/\\s/:/2' from replace nth occurence of string in each line of a text file But it only replaces the second occurence.


input

TEDL15_TRAINING_00018 2 0.047883321 6 0.041573718 7 0.020443868 8 0.035350464 11 0.026124746 16 0.035317142 22 0.014992127

TEDL15_TRAINING_00015 2 0.076135024 66 0.036367059 68 0.05614619 106 0.040146504 113 0.038728137 

output

TEDL15_TRAINING_00018 2:0.047883321 6:0.041573718 7:0.020443868 8 0.035350464 11:0.026124746 16:0.035317142 22:0.014992127

TEDL15_TRAINING_00015 2:0.076135024 66:0.036367059 68:0.05614619 106: 0.040146504 113:0.038728137 

Supposing your text is stored in a file named test.txt:

sed -e 's/ \([[:digit:]]\+\) \([[:digit:]].[[:digit:]]\+\)/ \1:\2/g' test.txt

Explanation:

Basically your input numbers have the following format (where _ represents a space):

_digit+_digit.digit+ 

So the above just look for this pattern, capture its groups and rewrite them by inserting a ":"

There's an awk method but I'm not sure it's the best choice in this case:

awk '{for (i=1;i<=NF;i+=2)
     if (i==NF) {
       printf ("%s %s\n",$i,$(i+1))
       }
      else
       {
       printf ("%s %s:",$i,$(i+1))
       }
     }'

Looks a little ugly but works in your case.

This is a case where perl is the more readable option.

sed 's/\([^[:space:]]\+[[:space:]]\+[^[:space:]]\+\)[[:space:]]\+/\1:/g'
awk '{for (i=1; i<=NF; i+=2) printf "%s%s %s", (i==1 ? "" : ":"), $i, $(i+1); print ""}'
perl -pe 's/(\S+\s+\S+)\s+/$1:/g'

使用不带搜索模式相同部分的sed的行为和g选项

sed 's/^/- /;s/$/ /;s/\([^[:blank:]]\{1,\}\)[[:blank:]]\{1,\}\([^[:blank:]]\{1,\}[[:blank:]]\)/\1|\2/g;s/..//;s/.$//' YourFile

This might work for you (GNU sed):

sed -r 's/(\s\S+)\s/\1:/g' file

This replaces throughout the line a space followed by one or more non-spaces followed by a space by a space followed by one or more non-spaces followed by a colon.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM