我正在尝试使用命令sed从Bash脚本中删除文本文件中的行。
以下是此功能的工作原理 用户输入记录号 程序搜索记录号 程序删除记录
这是我的代码:
r=$(grep -h "$record" student_records.txt|cut -d"," -f1) #find the record that needs to be deleted
echo $line -->> This proves that previous command works
sed -i '/^$r/d' student_records.txt -->> this does not work
有什么想法吗?
答案 0 :(得分:0)
从文件中删除包含$record
的行:
grep -v "$record" student_records.txt >delete.me && mv -f delete.me student_records.txt
在上文中,$record
被视为正则表达式。这意味着,例如,句点是通配符。如果这是不需要的,请将-F
选项添加到grep
,以指定将$record
视为固定字符串。
考虑这两行:
r=$(grep -h "$record" student_records.txt|cut -d"," -f1) #find the record that needs to be deleted
echo $line -->> This proves that previous command works
第一行定义了一个shell变量r
。第二行打印shell变量line
,这是一个不受上一个命令影响的变量。因此,第二行不是第一行的成功测试。
sed -i '/^$r/d' student_records.txt -->> this does not work
观察表达式$r
出现在单引号内。 shell不会改变任何内部单引号。因此,$r
将保留一个美元符号,后跟r
。由于美元符号与行的末尾匹配,因此该表达式将不匹配任何内容。以下方法会更好:
sed -i "/^$r/d" student_records.txt
与grep
命令不同,上述sed
命令具有潜在的危险性。构造r
的值会很容易导致sed
做出令人惊讶的事情。因此,除非您信任获得r
的过程,否则请勿使用此方法。
record
匹配怎么办?如果有多个与record
匹配的行,则以下内容会从unterminated address regex
生成sed
错误:
r=$(grep -h "$record" student_records.txt|cut -d"," -f1)
sed -i "/^$r/d" student_records.txt
此错误是将shell变量扩展为sed
命令时可能发生的令人惊讶的结果的示例。
相比之下,这种方法会删除所有匹配的行:
grep -v "$record" student_records.txt >delete.me && mv -f delete.me student_records.txt