在UNIX中读取文件并进行操作

时间:2014-10-29 17:12:59

标签: unix awk

我有一个要求,我必须阅读文件并进行操作。如果在任何字段中找到它,我必须将单双引号替换为双引号。字段由|分隔。 请在下面找到更好的理解。

输入:

1234567|9393874|"Hi"|"How are "you""
98647489|20370483|"i am "good""|"what about "you""

输出:

1234567|9393874|"Hi"|"How are ""you"""
98647489|20370483|"i am ""good"""|"what about ""you"""

1 个答案:

答案 0 :(得分:0)

我会用另一个字符替换所有“边缘”引号,然后替换“内部”字符:

sed -e 's/|"/|_/g' -e 's/"|/_|/g' -e 's/"$/_/' file | sed 's/"/""/g' | sed 's/_/"/g'

它返回:

1234567|9393874|"Hi"|"How are ""you"""
98647489|20370483|"i am ""good"""|"what about ""you"""

一步一步:

$ sed -e 's/|"/|_/g' -e 's/"|/_|/g' -e 's/"$/_/' a 
1234567|9393874|_Hi_|_How are "you"_
98647489|20370483|_i am "good"_|_what about "you"_
$ sed -e 's/|"/|_/g' -e 's/"|/_|/g' -e 's/"$/_/' a | sed 's/"/""/g' 
1234567|9393874|_Hi_|_How are ""you""_
98647489|20370483|_i am ""good""_|_what about ""you""_
$ sed -e 's/|"/|_/g' -e 's/"|/_|/g' -e 's/"$/_/' a | sed 's/"/""/g' | sed 's/_/"/g'
1234567|9393874|"Hi"|"How are ""you"""
98647489|20370483|"i am ""good"""|"what about ""you"""