2015-04-12 50 views
-1

我試圖從命令行中獲取包含名稱的行號。 然後,我想用一個新名稱來更改該名稱。 然後打印新行。 我在這裏:更改shell中某行的內容

echo -n "enter name" 
read name 
grep -n "$name" file 

它會返回例如3項

1)Sofia : 432-4567 
2) 
3) 
echo "Which line will be changed?" 
read number 

現在我想在第1行, 和打印與羅瑞改變索菲亞:

The new entry is Lorie : 432-4567 
+0

對於那些誰回答,以及未來的讀者的好處:如果你_solves_問題的答案,請點擊旁邊的大對勾_accept it_;如果您找到答案_helpful_,請點擊向上箭頭圖標(您可以同時執行這兩個操作),然後點擊投票。請參閱[相關幫助中心文章](http://stackoverflow.com/help/someone-answers)。如果您的問題尚未得到充分解答,請提供反饋。 – mklement0

回答

0

嘗試使用bash

#!/usr/bin/env bash 

read -p "Enter name: " name 

grep -n "$name" file || { echo "'$name' not found in file." >&2; exit 1; } 

read -p "Which line do you want to change? " number 

# Note: You should check to make sure that a valid 
#  line number was entered. 

# Define variables containing the name to replace and its replacement. 
old=$name 
new='Lorie' 

# Use Sed to modify the line of interest in the input file. 
# A backup of the original file is saved as file.bak. 
# Note that, to avoid confusion, all literal parts of the Sed 
# script are maintained as *single*-quoted strings, with values from 
# shell variables *spliced in* (as variable references inside a *double*-quoted string). 
sed -i.bak "$number"' { s/^'"$old"' :/'"$new"' :/; }' file 

# Report the modified line. 
echo "The new entry is: $(sed -n "$number"' {p;q;}' file)" 

注意:如果你不希望要備份原文件,語法取決於你所使用的執行sed

  • GNU sedsed -i ... # simply do not append a value to -i
  • BSD sed,也使用OSX:sed -i '' ... # -i requires a separate, empty argument
  • 如果您sed不支持-i乾脆,用下面的習慣:
    • sed ... file > tmpfile && mv tmpfile file
+0

嗨需要索菲亞和洛瑞變易 – Leili

+0

@雷利:查看更新。 – mklement0

+0

我得到了這個錯誤Sed:-e表達式#1,字符1:缺少命令 – Leili