更改shell中行的内容

时间:2015-04-12 21:17:53

标签: bash shell sed

我试图从命令行获取包含名称的行号。 然后我想用新名称更改该名称。 然后打印新行。 我在这里:

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行用Lorie改变索菲亚, 并打印:

The new entry is Lorie : 432-4567

1 个答案:

答案 0 :(得分: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