在shell脚本中使用sed命令进行子字符串并替换需要的位置
我正在在文本文件上处理数据,我找不到SED的方法来在固定位置选择子字符串并替换。
这就是我所拥有的:
X|001200000000000000000098765432|1234567890|TQ
这就是我所需要的:
‘X’,’00000098765432’,’1234567890’,’TQ’
以下代码在SED中给出了我需要的子字符串(00000098765432),但不覆盖位置,
echo “ X|001200000000000000000098765432|1234567890|TQ” | sed “s/
*//g;s/|/‘,’/g;s/^/‘/;s/$/‘/“
您可以帮助我吗?
I’m dealing data on text file and I can’t find a way with sed to select a substring at a fixed position and replace it.
This is what I have:
X|001200000000000000000098765432|1234567890|TQ
This is what I need:
‘X’,’00000098765432’,’1234567890’,’TQ’
The following code in sed gives the substring I need (00000098765432) but not overwrites position to need
echo “ X|001200000000000000000098765432|1234567890|TQ” | sed “s/
*//g;s/|/‘,’/g;s/^/‘/;s/$/‘/“
Could you help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我将使用
SED
,而是使用awk
。给出输出:
这是其工作原理:
fs
= field separator(在输入中)ofs
=输出字段分隔仪(您希望输出的方式被划定的方式)>开始
- >将其视为设置配置的地方。它只运行一次。因此,您是在说希望输出被划界,并将输入界定为界限。substr($ 2,17,14)
- >以$ 2的价格(即第二个字段 - awk从1开始计数,然后在上面应用子字符串。17表示开始角色位置,14表示从该位置开始的字符数量),我认为这比这比可读性更高且可维护您拥有的SED版本。
Rather than
sed
, I would useawk
for this.Gives output:
Here is how it works:
FS
= Field separator (in the input)OFS
= Output field separator (the way you want output to be delimited)BEGIN
-> think of it as the place where configurations are set. It runs only one time. So you are saying you want output to be comma delimited and input is pipe delimited.substr($2,17,14)
-> Take $2 (i.e. second field - awk begins counting from 1 - and then apply substring on it. 17 means the beginning character position and 14 means the number of characters from that position onwards)In my opinion, this is much more readable and maintainable than sed version you have.
如果您想将报价放入,我仍然会使用
awk
。如果您只想使用
sed
,请注意,您要删除16个字符,但实际上您只删除14个字符。If you want to put the quotes in, I'd still use
awk
.If you just want to use
sed
, note that you say above you want to remove 16 characters, but you are actually only removing 14.使用
sed
Using
sed
使用任何Posix Awk:
Using any POSIX awk:
不像我希望的那样优雅,但它可以完成工作:
经过测试和确认在
gnu gawk 5.1.1
,mawk 1.3.4
,mawk 1.9 .9.6
和macOSX NAWK
-
4chan teller
not as elegant as I hoped for, but it gets the job done :
Tested and confirmed working on
gnu gawk 5.1.1
,mawk 1.3.4
,mawk 1.9.9.6
, andmacosx nawk
—
The 4Chan Teller