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