2011-04-06 92 views
4

我正在编写一个shell脚本,我想将alias添加到.bashrc文件中alias列表的末尾。我在想sed会起作用,只是不知道如何找到以alias开头的最后一行,然后在下一行再添加alias使用sed将别名添加到.bashrc文件中的别名列表

+0

请给出一个示例输入和期望的输出。 – SiegeX 2011-04-06 22:23:45

回答

16

为什么你需要将它添加到“别名列表”?如果你没有,你没有在这个问题指定其他要求,只是您的别名追加到.bashrc

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

通常,.bashrc加载.alias - 使其更加明显,但.bashrc的结尾也起作用。 – Tanktalus 2011-04-07 01:51:52

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 

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

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 
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