Substitute vertical lines in Bash

无人久伴 提交于 2021-01-27 06:47:43

问题


I'm having a hard time finishing my script since there's this part which doesn't function the way I wanted it to be.

I have this line in my script:

cat /home/tmp/temp1.txt | awk '{gsub("~",RS);gsub("*",RS);print}' >  /home/tmp/temp.txt

It works fine, yes. But when I do something like this:

cat /home/tmp/temp1.txt | awk '{gsub("|",RS);print}' >  /home/tmp/temp.txt

It's not working at all. I wanted to change all my vertical bars into new line and yet I can't achieve it. Please help me with this. Thanks


回答1:


You can do all the replacements in a single awk like this:

awk '{gsub(/[*~|]/, RS)} 1' /home/tmp/temp1.txt

Pipe is otherwise used for regex alternation that needs escaping. However inside the character class [...] pipe or asterisk need not be escaped as shown above.

It is also better to use /.../ regex literal in gsub function instead of quoted string.




回答2:


If you really only want to replace vertical bars with newlines, you can do that much more succinctly with tr which translates characters:

echo "hi|there|my|friend"   |    tr '|' '\n'
hi
there
my
friend

Or, if you are using a file:

tr '|' '\n'  < /home/tmp/temp.txt


来源:https://stackoverflow.com/questions/32369035/substitute-vertical-lines-in-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!