[英]How to replace spaces with points at even positions in a line using linux command
我有一个文件,试图将偶数位置的间距替换为两点。 我可以使用什么linux命令来执行此操作?
我尝试了以下sed命令sed 's/\\s/:/2'
从文本文件的每一行中替换字符串的第n次出现,但是它仅替换了第二次出现。
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
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
假设您的文本存储在名为test.txt的文件中:
sed -e 's/ \([[:digit:]]\+\) \([[:digit:]].[[:digit:]]\+\)/ \1:\2/g' test.txt
说明:
基本上,您的输入数字采用以下格式(其中_代表空格):
_digit+_digit.digit+
因此,上面只是寻找此模式,捕获其组并通过插入“:”来重写它们
有一种awk方法,但在这种情况下我不确定这是最佳选择:
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))
}
}'
看起来有点丑陋,但适用于您的情况。
在这种情况下,perl是更易读的选项。
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
这可能对您有用(GNU sed):
sed -r 's/(\s\S+)\s/\1:/g' file
这将在整个行中替换一个空格,然后是一个或多个非空格,然后是空格,然后是空格,再是一个或多个非空格,然后是冒号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.