linux - sed如何在第一行末尾添加带竖线的变量

标签 linux bash shell sed

我想将带有字符串的变量附加到 my_file 的第一行

sed -i "1 s/$/$my_variable/"~/my_file

现在我有这个:

42 192.168.1.1 string_from_my_variable

它有效。但是任务变得更难了,现在我需要在 string_from_my_variable

之前添加定界符

我试过sed -i "1 s#$#\|\$my_variable#"~/my_file,当然没有用。我需要这个:

42 192.168.1.1 | string_from_my_variable

我该怎么做?感谢您的关注。

最佳答案

由于您想处理来自 shell 变量的文字字符串,我会使用 awk:

awk -v extra="$my_variable" 'NR == 1 { $0 = $0 "   |" extra } 1' file

将额外的字符串添加到第一行,最后的 1 是编写 1 { print $0 } 的最短方式,因此每一行都会被打印出来。

要覆盖您的原始文件:

# GNU Awk
awk -i inplace -v extra="$my_variable" 'NR == 1 { $0 = $0 "   |" extra } 1' file
# any Awk
awk -v extra="$my_variable" 'NR == 1 { $0 = $0 "   |" extra } 1' file > tmp && mv tmp file

关于linux - sed如何在第一行末尾添加带竖线的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47260121/

相关文章:

linux - centos如何写脚本文件每天半夜重启tomcat

bash - 在 jmeter 中运行 sh 脚本

bash - 如何在 bash for 循环中构建复合条件

linux - 为什么在/proc/interrupts 中不显示启用rtc 中断?

linux - 如何在非 Windows 操作系统的 WiX 安装程序中获取操作系统名称?

Linux Mint - 永久添加环境变量

bash - While 循环在 Bash 中的第一行之后停止读取

windows - 如何在 Teamcity Windows 代理上运行 shell 脚本?

c - 如何将包含指针的结构从用户空间复制到内核

linux - 如果存在另一行,则 Bash 替换行