【问题标题】:BASH - Print new entry to file with line number includedBASH - 将新条目打印到包含行号的文件
【发布时间】:2022-01-19 02:17:25
【问题描述】:

我不知道如何在文件中添加一行,然后只用行号打印该行。这是我当前打印所有行的代码:

printf "Would you like to add an entry to the file? Type yes or y? "
read addline
input=$addline
if [ $input = 'yes' ] || [ $input = 'y' ]
then
    printf "Please enter a new name: First Last: "
    read newname
    printf "Please enter a new telephone number: xxx-xxx-xxxx: "
    read phone
    printf "Please enter a street address only: xxx Example Street: "
    read street
    printf "Please enter your birthdate: xx-xx-xxxx: "
    read birth
    printf "Please enter salary: xxxxxxx: "
    read salary
    echo -e "$newname:$phone:$street:$birth:$salary" >> datafile.txt
else
    printf "\nYou did not type yes or y. Run the program again.\n"
    exit
fi
printf "\nYour entry has been saved.\n" 
sort -k2 $file | nl

【问题讨论】:

  • 为什么需要input=$addline?为什么不只是read input
  • 您为什么要使用-e 选项来代替echo?用户通常不会输入带有转义序列的数据。
  • echo -e - 不确定,我删除了它,它可以工作。
  • input = $addline - 谢谢。

标签: bash file line


【解决方案1】:

您可以使用grep-n 选项来打印匹配行及其行号。

grep -n -F -x "$newname:$phone:$street:$birth:$salary" datafile.txt

【讨论】:

  • 有没有办法分隔行号?当我输入 1:1:1:1:1 时,输出为 7:1:1:1:1:1。行号看起来像是条目的一部分。
  • 您可以通过管道将其传递给sed 以将第一个: 替换为空格。
【解决方案2】:

感谢 Barmar 的帮助,我找到了答案。

cat -n $文件 | grep "$newname:$phone:$street:$birth:$salary"

谢谢大家。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 2013-03-23
    • 2011-01-29
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    相关资源
    最近更新 更多