使用Shell从字符串中间删除第n个字符 [英] Remove nth character from middle of string using Shell
问题描述
我一直在搜索google,但找不到如何执行此操作的示例.我也不了解如何为SED构造正则表达式的概念,因此我希望有人可以向我解释一下.
I've been searching google for ever, and I cannot find an example of how to do this. I also do not grasp the concept of how to construct a regular expression for SED, so I was hoping someone could explain this to me.
我正在对包含以下文本行的文件运行bash脚本:2222,H,73.82,04,07,2012
I'm running a bash script against a file full of lines of text that look like this: 2222,H,73.82,04,07,2012
我需要使它们看起来都像这样:2222,H,73.82,04072012
and I need to make them all look like this: 2222,H,73.82,04072012
我需要删除最后两个逗号,即该行中的第16和19个字符.有人可以告诉我该怎么做吗?我本来要使用colrm,这很简单,但是我似乎无法在CYGWIN中安装它.请谢谢!
I need to remove the last two commas, which are the 16th and 19th characters in the line. Can someone tell me how to do that? I was going to use colrm, which is blessedly simple, but i can't seem to get that installed in CYGWIN. Please and thank you!
推荐答案
我将使用 awk
:
awk -F',' -v OFS=',' '{ print $1, $2, $3, $4$5$6 }' inputfile
这将获取一个CSV文件,并打印第一个,第二个和第三个字段,每个字段后跟输出字段分隔符(,"
),然后将第四个,第五个和第六个字段串联起来.
This takes a CSV file and prints the first, second and third fields, each followed by the output field separator (","
) and then the fourth, fifth and sixth fields concatenated.
我个人认为,这比 sed
中基于正则表达式的解决方案更易于阅读和维护,并且如果您的任何列变宽(变窄),它将很好地应对.).
Personally I find this easier to read and maintain than regular expression-based solutions in sed
and it will cope well if any of your columns get wider (or narrower!).
这篇关于使用Shell从字符串中间删除第n个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!