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

时间:2011-04-06 22:20:59

标签: bash shell

我正在编写一个shell脚本,我想在alias文件的alias列表的末尾添加.bashrc。我认为sed会有效,但不确定如何找到以alias开头的最后一行,然后在下一行添加另一行alias

4 个答案:

答案 0 :(得分:17)

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

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

答案 1 :(得分:4)

当我听到“在最后的事情之后做点什么”之后,我想到了当我看到第一件事时反转文件并做一些事情:

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

答案 2 :(得分:2)

恕我直言,这在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

对我有用的更全面的版本是

$ name=b
$ replacement=barney
sed -i.bak -n -e '
:START
/^[[:space:]]*alias/ b NEXTALIAS
# not an alias, print it as-is and go to next line
p
b
:NEXTALIAS
# start processing this alias line
/^[[:space:]]*alias[[:space:]][[:space:]]*'"$name"'/ b REPLACE
/^[[:space:]]*alias/ b PRINT

# found the end of the alias block, insert the alias here
:INSERT
# grab the indentation back from the hold space
x
s/$/alias '"$name='$replacement'"'/
p
x
b REST

:PRINT
# remember how the last alias line was indented...
h
s/^\([[:space:]]*\).*/\1/
x
# ... and print the line
p
n
b NEXTALIAS

:REPLACE
# we found an existing alias with a matching name, replace it
# I add single quotes around replacement so that the caller can write
# replacement='echo something' rather than replacement="'echo something'"
s/\(.*\)alias[[:space:]][[:space:]]*'"$name"'.*/\1alias '"$name='$replacement'"/'
b REST

:REST
# we made it past the aliases block, just print the remaining lines
p
n
b REST
' aliases

$ diff -u aliases.bak aliases
--- aliases.bak 2011-04-07 09:09:26.000000000 +1000
+++ aliases     2011-04-07 09:11:05.000000000 +1000
@@ -2,7 +2,7 @@
 echo blah

 alias a=apple
-alias b=banana
+alias b='barney'
 alias c=carrot

 echo something else

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

答案 3 :(得分:0)

如果您不能使用更好的脚本语言,

awk是使用的工具。没有必要使用 sed`

awk 'FNR==NR&&/alias/{s=FNR;next}FNR==s{ $0=$0"\nalias=new alias\n"}NR>FNR' .bashrc .bashrc > temp && mv temp .bashrc