我的档案:
"gd$postalAddress":[{"rel":"http://schemas.google.com/g/2005#home"
"$t":"randomtext"}]}
"gd$postalAddress":[{"rel":"http://schemas.google.com/g/2005#home"
"$t":"randomtext222"}]}
"title":{"type":"text"
"$t":"randomtext"}
"gd$postalAddress":[{"rel":"http://schemas.google.com/g/2005#home"
"$t":"randomtext"}]}
我需要在postalAddress之后改变行上的$ t,而不是在带有标题的行之后改变$ t。
这将打印我想要更改的行。
sed -n '/postalAddress/ {n;p}' file.txt
这将打印我想要更改的行,其中包含更改:
sed -n '/postalAddress/ {n;p}' file.txt | sed 's/"$t":"/CHANGE/'
但是如何在我的文件中更改此内容?
以下是我的文件的样子:
"gd$postalAddress":[{"rel":"http://schemas.google.com/g/2005#home"
"CHANGE":"randomtext"}]}
"gd$postalAddress":[{"rel":"http://schemas.google.com/g/2005#home"
"CHANGE":"randomtext222"}]}
"title":{"type":"text"
"$t":"randomtext"}
"gd$postalAddress":[{"rel":"http://schemas.google.com/g/2005#home"
"CHANGE":"randomtext"}]}
答案 0 :(得分:3)
使用sed
sed '/postalAddress/{n;s/\$t/CHANGE/;}' file
"gd$postalAddress":[{"rel":"http://schemas.google.com/g/2005#home"
"CHANGE":"randomtext"}]}
"gd$postalAddress":[{"rel":"http://schemas.google.com/g/2005#home"
"CHANGE":"randomtext222"}]}
"title":{"type":"text"
"$t":"randomtext"}
"gd$postalAddress":[{"rel":"http://schemas.google.com/g/2005#home"
"CHANGE":"randomtext"}]}
使用awk
即可:
awk '/postalAddress/ {print;getline;sub(/\$t/,"CHANGE")}1' file
"gd$postalAddress":[{"rel":"http://schemas.google.com/g/2005#home"
"CHANGE":"randomtext"}]}
"gd$postalAddress":[{"rel":"http://schemas.google.com/g/2005#home"
"CHANGE":"randomtext222"}]}
"title":{"type":"text"
"$t":"randomtext"}
"gd$postalAddress":[{"rel":"http://schemas.google.com/g/2005#home"
"CHANGE":"randomtext"}]}
将标记与awk
一起使用:
awk '/postalAddress/ {f=NR+1} f==NR {sub(/\$t/,"CHANGE");f=0}1 file
答案 1 :(得分:0)
你真的应该使用一种理解你的数据的语言,这似乎是JSON,所以也许是Python。但我们可以使用sed来做到这一点:
sed '/}]}/ s/"$t":"/CHANGE/' file.txt
"gd$postalAddress":[{"rel":"http://schemas.google.com/g/2005#home"
CHANGErandomtext"}]}
"gd$postalAddress":[{"rel":"http://schemas.google.com/g/2005#home"
CHANGErandomtext222"}]}
"title":{"type":"text"
"$t":"randomtext"}
"gd$postalAddress":[{"rel":"http://schemas.google.com/g/2005#home"
CHANGErandomtext"}]}
这取决于标点符号是你所关注的行的结尾,而不是那些你不关注的行。