简体   繁体   English

sed on Bash字符串变量

[英]sed on a Bash string variable

I have a variable: 我有一个变量:

temp='Some text \n Some words \n'

I would like to delete some of those lines with sed: 我想用sed删除其中一些行:

sed -e '1d' $temp 

I want to know if this is possible. 我想知道这是否可行。

When you pass your string as an argument, sed would interpret as a filename or a list of file names: 当您将字符串作为参数传递时, sed将解释为文件名或文件名列表:

sed -e '1d' "$temp"

Of course, that's not what you want. 当然,那不是你想要的。

You need to use here string <<< instead: 你需要在这里使用字符串<<<而不是:

temp=$'Some text\nSome words\nLast word'
sed '1d' <<< "$temp"

Output: 输出:

Some words
Last word

posix-compatible way to do this is: 与posix兼容的方法是:

temp="$(printf '%s\n' "$temp" | sed '1d')"

if you only need a bash-compatible solution see codeforester's answer , as the here string syntax is much better readable. 如果你只需要一个与bash兼容的解决方案,请参阅codeforester的答案 ,因为这里的字符串语法更易读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM