2011-04-06 4 views
4

alias.bashrc 파일의 alias 목록 끝에 추가하려는 쉘 스크립트를 작성하고 있습니다. sed으로 뭔가를 생각하고 있는데, alias으로 시작하는 마지막 줄을 찾는 방법을 모르면 다음 줄에 다른 alias을 추가하십시오.sed를 사용하여 .bashrc 파일의 별칭 목록 끝에 별칭 추가

+0

하십시오 예제 입력과 원하는 출력을 제공하십시오. – SiegeX

답변

16

왜 "별칭 목록"에 추가해야합니까? 당신이 질문에 지정하지 않은 추가 요구 사항이없는 경우, 단지 .bashrc에 별칭을 추가합니다

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

종종 .bashrc는 .alias를로드합니다. 더 명확하게 보이지만 .bashrc의 끝도 작동합니다. – Tanktalus

2

이럴이 펄, 파이썬에서 할 청소기/훨씬 용이 등

하지만 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 
012,351,641입니다은

명시 적으로 처리하지 않은 몇 가지 엣지 케이스가 있습니다. 예를 들어 두 개의 별칭 블록이있는 경우 어떻게해야합니까? 별칭 블록 중간에 주석 처리 된 별칭이있는 경우 어떻게합니까?

0

awk은 더 나은 스크립팅 언어를 사용할 수없는 경우 사용할 도구입니다. 내가, 내가 파일을 반대로 생각 "무엇 지난 후 무언가를"들을 때

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

을 sed` 사용하고 내가 처음 볼 때 뭔가를 할 필요가 없습니다 어떤 :

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