bash - 如何使用 sed 或 awk 在文件的特定行插入特定字符?

标签 bash unix awk sed

我想使用命令来编辑文件的特定行,而不是使用 vi。就是这样。如果该行以 # 开头,则替换 # 以使其取消注释。否则,添加 # 使其成为注释。我想使用 sed 或 awk。但它不会按预期工作。
这是文件

what are you doing now?
what are you gonna do? stab me?
this is interesting.
This is a test.
go big
don't be rude.

例如,如果不是以 # 开头,我只想在第 4 行 This is a test 的开头添加 # 。如果它以 # 开头,则删除 #

我已经通过 sed 和 gawk (awk) 尝试过

gawk -i inplace '$1!="#" {print "#",$0;next};{print substr($0,3,length-1)}' file 
sed -i /test/s/^#// file  # make it uncomment

sed -i /test/s/^/#/ file  # make it comment

我不知道如何使用 if else 使 sed 工作。我只能用一个命令来实现,然后使用另一个正则表达式来实现相反的操作。
使用gawk,作为主线工作。但它会弄乱其余的代码。

最佳答案

这可能对你有用(GNU sed):

sed '4{s/^/#/;s/^##//}' file

在第 4 行添加一个 # 到该行,如果有 2 个 # 将其删除。

也可以写成:

sed '4s/^/#/;4s/^##//' file

关于bash - 如何使用 sed 或 awk 在文件的特定行插入特定字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56784244/

相关文章:

awk - groupby/sum 第一列中的所有列相同的awk

bash - 嵌套的 Herodoc 操作顺序

c++ - 编译后 Unix 命令行无法运行程序,没有错误消息

c - C套接字中奇怪的while循环?

shell - 创建包含文件名的新文件并计算每个文件

awk:超出程序限制:最大字段数 size=32767

linux - GREP 或 AWK 复杂模式匹配 (linux)

bash - 使 rustc、cargo、rustup、rustdoc 命令在适用于 Linux 的 Windows 子系统中无需 sudo 即可运行

linux - 使用shell脚本获取网络中的图像列表

bash - 根据值删除 bash 中的行