繁体   English   中英

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

[英]Adding alias to end of alias list in .bashrc file using sed

我正在编写一个shell脚本,我想在.bashrc文件的alias列表的末尾添加一个alias 我正在考虑使用sed工作,只是不确定如何找到以alias开头的最后一行,然后在下一行添加另一个alias

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

echo "alias youralias='yourcmd'" >> /home/user/.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

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

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

如果你不能使用更好的脚本语言, 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM