[英]Bash: Replacing “” with newline character, using sed or tr
I'm trying to format output in a way that inserts newline characters after each 'line', with lines denoted by double quotes (""). 我正在尝试格式化输出的格式,在每行之后插入换行符,并用双引号(“”)表示行。 The quotes themselves are temporary and to be stripped in a later step.
引号本身是临时的,将在以后的步骤中删除。
Input: 输入:
"a",1,"aa""b",2,"bb"
Output: 输出:
a,1,aa
b,2,bb
I've tried: 我试过了:
sed 's/""/\n/'
sed 's/""/\/g'
tr '""' '\n'
But tr seems to replace every quote character and sed seems to insert \\n as text instead of a newline. 但是tr似乎替换了每个引号字符,而sed似乎将\\ n插入为文本而不是换行符。 What can I do to make this work?
我该怎么做才能使这项工作?
echo '"a",1,"aa""b",2,"bb"' |awk -v RS='""' '{$1=$1} {gsub(/"/,"")}1'
a,1,aa
b,2,bb
or using sed
: 或使用
sed
:
echo '"a",1,"aa""b",2,"bb"' |sed -e 's/""/\n/' -e 's/"//g' # OR sed -e 's/""/\n/;s/"//g'
a,1,aa
b,2,bb
awk
solution: Here the default record separator is changed from new line to ""
. awk
解决方案:在这里,默认记录分隔符从新行更改为""
。 So awk
will consider the EOL when it hits ""
. 因此,
awk
在遇到""
时将考虑EOL。
sed
solution: Here first ""
are converted into new line and second replacement is to remove "
from each line. sed
解决方案:这里将第一个""
转换为新行,第二个替换是从每行中删除"
。
neech@nicolaw.uk:~ $ cat file.txt
"a",1,"aa""b",2,"bb"
neech@nicolaw.uk:~ $ sed 's/""/\n/' file.txt | tr -d '"'
a,1,aa
b,2,bb
You seem to be dealing with POSIX sed
, which does not have support for the \\n
notation. 您似乎正在处理POSIX
sed
,它不支持\\n
表示法。 Insert an actual new-line into the pattern, either: 在模式中插入实际的换行符:
sed 's/""/\
/'
Or: 要么:
sed 's/""/\'$'\n''/'
Eg: 例如:
sed 's/""/\
/' | tr -d \"
Output: 输出:
a,1,aa
b,2,bb
As suggested by George Vasiliou if you have perl you could use: 如乔治·瓦西里乌(George Vasiliou)所建议,如果您有perl,则可以使用:
> echo '"a",1,"aa""b",2,"bb"' | perl -pe 's/""/"\n"/g;s/"//g'
This avoids the non portable sed problem. 这避免了非便携式sed问题。
Or for a crappy hack version. 或用于糟糕的hack版本。
Replace the "" with another character and then use tr (since tr should work with \\n) to replace it with \\n instead then remove the single " after. 将“”替换为另一个字符,然后使用tr(因为tr应该与\\ n一起使用)将其替换为\\ n,然后再删除单个“”。
So you can get the "" replaced with newline like this: 因此,您可以将“”替换为换行符,如下所示:
sed 's/""/#/g' | tr '#' '\n'
Then the rest follows: 然后其余的如下:
> echo '"a",1,"aa""b",2,"bb"'| sed 's/""/#/g' | tr '#' '\n' | sed 's/\"//g'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.