【发布时间】:2017-05-03 02:47:55
【问题描述】:
我有一个名为 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
)
【问题讨论】:
-
@pvg ive 将 t3=$(tr ...) 替换为 t3=$(sed "s/$t1/$t2/g")。它没有工作
-
单次调用 sed 就可以做到这一点,你不需要其他任何东西。链接的答案之一与您的问题相同,使用它。
标签: linux bash shell ubuntu sed