3

I have a variable:

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

I would like to delete some of those lines with sed:

sed -e '1d' $temp 

I want to know if this is possible.

codeforester
  • 39,467
  • 16
  • 112
  • 140
Ursescu Ionut
  • 97
  • 1
  • 6

2 Answers2

4

When you pass your string as an argument, sed would interpret as a filename or a list of file names:

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
codeforester
  • 39,467
  • 16
  • 112
  • 140
  • 4
    Notice the `\n` only is a linebreak here because of `$'\n'` quoting. With just `'\n'`, it would be a literal `\n`. – Benjamin W. Mar 15 '17 at 19:04
  • See [Difference between single and double quotes in Bash](https://stackoverflow.com/a/42082956/6862601) as well. – codeforester Sep 21 '17 at 04:51
0

posix-compatible way to do this is:

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.

Community
  • 1
  • 1
Samuel Kirschner
  • 1,135
  • 1
  • 12
  • 18