[英]sed unable to remove from files
I am using ubuntu shell; 我正在使用ubuntu shell; I am suppose to read user input and delete the line in the file. 我想读取用户输入并删除文件中的行。 However when I run it, the terminal shows all data after deleting but my file remains untouched at all with no deletion. 但是,当我运行它时,终端会在删除后显示所有数据,但是我的文件完全保持不变,没有删除。 How do I ignore case for sed? 如何忽略sed的大小写?
Data: 数据:
The Small:Sir King:23.0:30:5
The Big:Sir King:28.0:40:7
The Middle:Sir King:98.9:20:8
Code: 码:
echo "Please enter data1: "
read data1
echo "Please enter data2: "
read data2
sed "/$data1:$data2/d" sampleDB.txt
When i type The Middle, Sir King it display this in terminal: 当我输入The Middle,金爵士时,它将在终端中显示:
The Small:Sir King:23.0:30:5
The Big:Sir King:28.0:40:7
But my file still have the The Middle:Sir King:98.9:20:8
但是我的文件仍然有The Middle:Sir King:98.9:20:8
Use -i option to do sed replace inplace in the file as below: 使用-i选项在文件中执行sed替换,如下所示:
sed -i "/$data1:$data2/d" sampleDB.txt
if you wish to create back up of original file before modifying the file then use it as: 如果您希望在修改文件之前创建原始文件的备份,则可以将其用作:
sed -i.bak "/$data1:$data2/d" sampleDB.txt
Now you will have additional file sampleDB.txt.bak without any modifications and original file sampleDB.txt with lines deleted. 现在,您将拥有没有任何修改的其他文件sampleDB.txt.bak,以及删除了行的原始文件sampleDB.txt。
What you have now is a very dangerous way to do it. 您现在拥有的是一种非常危险的方式。 You're using regexps when you want strings, and you're matching across the whole line not specific fields. 需要字符串时使用正则表达式,并且整行匹配而不是特定字段。
BACK UP YOUR FILE then try it if the user inputs .*
for both inputs. 如果用户为两个输入都输入。 .*
,则备份文件,然后尝试一下。 Now try it if they enter King
and 2
. 现在尝试如果他们输入King
和2
。 I'd guess those would NOT be desirable results. 我猜这些将不是理想的结果。
You should really be using awk since it can operate on specific fields using string comparison and so solve both problems: 您确实应该使用awk,因为它可以使用字符串比较在特定字段上进行操作,因此可以解决两个问题:
awk -F: -v d1="$data1" -v d2="$data2" '!($1==d1 && $2==d2)' sampleDB.txt > tmp &&
mv tmp sampleDB.txt
to ignore case would be: 忽略大小写是:
awk -F: -v d1="$data1" -v d2="$data2" '!(tolower($1)==tolower(d1) && tolower($2)==tolower(d2))' sampleDB.txt > tmp &&
mv tmp sampleDB.txt
With GNU awk you could use IGNORECASE
and -i inplace
to make it briefer if you like, see the man page. 使用GNU awk,您可以使用IGNORECASE
和-i inplace
使其更简短,请参见手册页。
instead of 代替
sed "/$data1:$data2/d" sampleDB.txt
try 尝试
sed -i "/$data1:$data2/Id" sampleDB.txt
the I
flag in the command line will ignore any upper/lower case. 命令行中的I
标志将忽略任何大写/小写字母。
你应该试试:
sed "/d${data1}:${data2}" sampleDB.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.