问题
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