[英]Sed how to add variable with vertical bar to the end of first line
i want to append variable with string to the first line of my_file
我想将带字符串的变量附加到
my_file
的第一行
sed -i "1 s/$/ $my_variable/" ~/my_file
Now i have this: 现在我有这个:
42 192.168.1.1 string_from_my_variable
It works. 有用。 But the task become harder, now i need to add delimiter before
string_from_my_variable
但是任务变得更加困难,现在我需要在
string_from_my_variable
之前添加定界符
I tried to sed -i "1 s#$# \\|\\$my_variable#" ~/my_file
, of course it does not help. 我试图
sed -i "1 s#$# \\|\\$my_variable#" ~/my_file
,当然没有帮助。 I need to have this: 我需要这个:
42 192.168.1.1 | string_from_my_variable
How can i do this ? 我怎样才能做到这一点 ? Thanks for your attention.
感谢您的关注。
Since you want to deal with literal strings that come from a shell variable, I would go with awk: 由于您要处理来自shell变量的文字字符串,因此我将使用awk:
awk -v extra="$my_variable" 'NR == 1 { $0 = $0 " |" extra } 1' file
Add the extra string to the first line and 1
at the end is the shortest way to write 1 { print $0 }
, so every line gets printed. 将多余的字符串添加到第一行,最后的
1
是写1 { print $0 }
的最短方法,因此每行都会被打印。
To overwrite your original file: 覆盖原始文件:
# 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
我已经发现:
sed -i "1 s/$/ \\|$my_variable/" ~/my_file
I think there's a coincidence in your command sed -i "1 s#$# \\|\\$my_variable#"
, the $#
is a special parameter in the double quotation marks( "" ), which means the number of parameters are given , you can get more informations by man bash
: 我认为您的命令
sed -i "1 s#$# \\|\\$my_variable#"
有一个巧合, $#
是双引号( “” )中的特殊参数 ,这意味着给出了参数数量 ,您可以通过man bash
获取更多信息:
Special Parameters # Expands to the number of positional parameters in decimal.
so, your command is illegal. 因此,您的命令是非法的。
# $# is a special parameter, so the command is illegal:
$ sed "1s#$# |${my_variable}#" my_file
sed: -e expression #1, char 32: unterminated `s' command
# when used ', the special meaning of $# is gone,
# and the command is legal, but doesn't work for your expection:
$ sed '1s#$# |${my_variable}#' my_file
42 192.168.1.1 |${my_variable}
# add a space beteween `$#`, and the command is legal too,
# but still doesn't work for your expection:
$ sed "1s#$ # |${my_variable}#" my_file
42 192.168.1.1
you can use a different delimiter instead of #
: 您可以使用其他定界符代替
#
:
my_variable="string_from_my_variable"
sed -i "1s/$/ |${my_variable}/" ~/my_file
PS: PS:
\\
before $my_variable
should NOT exist. $my_variable
之前的\\
不应该存在。 \\
before |
\\
之前|
is unnecessary if the delimiter is NOT |
|
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.