使用sed将别名添加到.bashrc文件中别名列表的末尾

使用sed将别名添加到.bashrc文件中别名列表的末尾,bash,shell,Bash,Shell,我正在编写一个shell脚本,希望在.bashrc文件的别名列表的末尾添加一个别名。我在想用sed做点什么会有用,只是不知道如何找到以alias开头的最后一行,然后在下一行添加另一个alias为什么需要将其添加到“别名列表”中?如果您没有问题中未指定的其他要求,只需将别名附加到。bashrc: echo "alias youralias='yourcmd'" >> /home/user/.bashrc 在Perl、Python等语言中,这更容易/更干净 但如果必须使用sed,那么这

我正在编写一个shell脚本,希望在
.bashrc
文件的
别名
列表的末尾添加一个
别名。我在想用
sed
做点什么会有用,只是不知道如何找到以
alias
开头的最后一行,然后在下一行添加另一个
alias

为什么需要将其添加到“别名列表”中?如果您没有问题中未指定的其他要求,只需将别名附加到
。bashrc

echo "alias youralias='yourcmd'" >> /home/user/.bashrc

在Perl、Python等语言中,这更容易/更干净

但如果必须使用sed,那么这里有一个起点:

$ sed -ne ':START
/alias/b ALIASES
p
b
:ALIASES
p
n
/alias/b ALIASES
i \
alias foo=bar
:REST
p
n
b REST
' < aliases > aliases.new
$ diff -u aliases aliases.new
--- aliases     2011-04-07 08:30:30.000000000 +1000
+++ aliases.new 2011-04-07 08:34:09.000000000 +1000
@@ -3,6 +3,7 @@

 alias a=apple
 alias b=banana
+alias foo=bar

 echo something else
$ mv aliases.new aliases

请注意,有些边缘情况我没有明确处理。例如,如果有两个别名块,该怎么办?如果在别名块中间有注释的别名等,

<代码> AWK< /Cord>是如果不能使用更好的脚本语言使用的工具。无需使用
sed`

awk 'FNR==NR&&/alias/{s=FNR;next}FNR==s{ $0=$0"\nalias=new alias\n"}NR>FNR' .bashrc .bashrc > temp && mv temp .bashrc
当我听到“在最后一件事之后做点什么”时,我会想把文件倒过来,当我看到第一件事时做点什么:

tac .bashrc | 
awk -v newalias="alias new=foo" '$1 == "alias" {print newalias} 1' | 
tac > .bashrc.new
mv .bashrc .bashrc.$(date +%Y%m%d%H%M%S) && mv .bashrc.new .bashrc

请给出一个输入和所需输出的示例。通常,.bashrc加载.alias-使其更加明显,但.bashrc的结尾也可以工作。
tac .bashrc | 
awk -v newalias="alias new=foo" '$1 == "alias" {print newalias} 1' | 
tac > .bashrc.new
mv .bashrc .bashrc.$(date +%Y%m%d%H%M%S) && mv .bashrc.new .bashrc