linux - 用shell脚本中的空行替换文件的一行?

标签 linux bash shell ubuntu sed

<分区>

我有一个名为 catalog 的文本文件,其中每一行都有一个名字、一个姓氏、一个城市和一个电话号码,如下所示:

John McJohn Detroit 0301234568
Donald Duck Lake_City 1234567890
Deez Nutz Oxford 2305985531

我想编写一个脚本,它将一个关键字作为参数,并将其行替换为带有空行的关键字。

这是我到目前为止的进展:

t1=$(grep $2 catalog)      #$2 is the keyword
echo the lines with that keyword are:
echo $t1

t2=$(echo)                       #a blank line

t3=$(tr '$t1' '$t2' < catalog)  #replacing each line with the keyword with a space

echo The lines have been deleted  #not really, they have been replaced with a space

cat catalog

这根本不会改变文件。

我已经尝试了很多 sed 表达式,但都没有成功(我在旧的 xubuntu 版本上运行脚本,所以我不知道 sed 是否应该适用于此)。

我曾尝试用“\n”替换“t2=$(echo)”,但如果失败得很惨。

这是怎么做到的? 是否可以将每一行替换为空白行的模式?

(可能且“工作正常”的答案:

t1=$(grep $2 catalog)     
echo the lines with that keyword are:
echo $t1
sed "./*$t1.*/s///" catalog
sed "./*$t1.*/s///" catalog > catalogtemp
mv catalogtemp catalog

)

最佳答案

使用 sed:

$ t1="Donald";
$ sed "s/.*$t1.*//" file
John McJohn Detroit 0301234568

Deez Nutz Oxford 2305985531

就地编辑文件,请使用-i fag:

sed -i "s/.*$t1.*//" file

编辑:

避免不需要的参数扩展的更安全的语法:

sed 's/.*'"$t1"'.*//' file

关于linux - 用shell脚本中的空行替换文件的一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41199072/

相关文章:

c - 在 linux 中添加系统调用时出现 'ímplicit declaration of function' 错误

linux - 打开多个网页,使用 wget 并合并输出

Bash 关联数组在 (...) 列表中初始化?

linux - 将多行的输出列分配给不同的变量?

linux - 辅助数据 : ‘IP_RECVIF’ undeclared (first use in this function)

php - UTF-8贯穿始终

linux - 如何使用sed命令

bash - 使用sed将一些大写字符替换为小写字符

python - VirtualEnv 从 bash 脚本初始化

linux - UNIX Case 语句中的模式匹配