【发布时间】:2013-11-17 10:48:04
【问题描述】:
我需要找到文件的最后第三行,如果是“}”,我应该用“}”替换它
我在想 awk 和 sed 这会找到文件的最后第三行
PATTERN=$(awk '{v[c++]=$0}END{print v[c-3]}' $file)
我想用
sed -i 's/$PATTERN/}/' $file
但这是错误的 不知道怎么继续
【问题讨论】:
我需要找到文件的最后第三行,如果是“}”,我应该用“}”替换它
我在想 awk 和 sed 这会找到文件的最后第三行
PATTERN=$(awk '{v[c++]=$0}END{print v[c-3]}' $file)
我想用
sed -i 's/$PATTERN/}/' $file
但这是错误的 不知道怎么继续
【问题讨论】:
这个awk 应该这样做(最后第三行more 已清除)
cat file
one
two },
three
four
more }, test }, hi
five },
yes
awk '{v[++c]=$0}END {for (i=1;i<=NR;i++) {if (v[c-3]~"},") gsub(/},/,"}",v[c-3]);print v[i]}}' t
one
two },
three
four
more }, test }, hi
five },
yes
【讨论】:
awk (some commands) file > tmp && mv tmp file 这会将更改写回file
c++ 增量变量,因此数组将从0 开始,更改为++c PS,唯一使用单个命令的解决方案awk :)跨度>
我需要找到文件的最后第三行,如果是“}”,我应该 用“}”替换它
使用tac 和sed:
tac filename | sed '3s/^};$/}/' | tac
在 MacOS 上,您可以说:
sed '1!G;h;$!d' filename | sed '3s/^};$/}/' | sed '1!G;h;$!d'
【讨论】: